You are not logged in.

Change Language:

Freelancer? Consultant? Check out: WorkTrail - Time Tracking made easy
Board » Django » Views » View using 2 models

Alright, I'm pretty new to Django and I've got this problem I can't quite solve.

I basically have two models, wich I use to put blog articles into categories. One is a Category and the other is a Subject. So in my categories I might have ('Programming', 'Music', 'Essays') and my subjects are listed under those various categories. So under Programming I might have ('Python', 'PHP', 'ASM').

Here a stripped down version of my models :

class Category(models.Model):
name = models.CharField(_('Categorie'), max_length=100)

class Subject(models.Model):
name = models.CharField(_('Forum'), max_length=100)
description = models.CharField(_('Description'), max_length=250)
category = models.ForeignKey(Category)

Now, what I try to do in my view, is to loop through the categories and list each subject it contains. Someone can help me ?
django automatically creates reverse attributes for ForeignKey attributes.. by default they are called <model name>_set .. so in your case your view would put a list of categories into the context and you would iterate in the template like:

  {% for category in category_list %}
    My Category: {{ category.name }}
    {% for subject in category.subject_set.all %}
      subject: {{ subject.name }}
    {% endfor %}
  {% endfor %}


you can obviously also create your own method in the Category model to retrieve subjects in a specialized way, or create a proxy in the view.. but usually this is neither required nor desirable :)
Thanks !





Powered by Sphene Community Tools