0

Lets say I have 2 model class. Category has a name and multiple tags and Tag has a name, can be visible or not.

EDIT : Lets say that I have a list of categories and for each category I would like to only display the tags that have visible=True, how should I proceed ?

    class Category(models.Model):
         name = models.CharField(max_length=255, unique=True)
         tags = models.ManyToManyField(Tag)

    class Tag(models.Model):
         name = models.CharField(max_length=255, unique=True)
         visible = models.BooleanField(default=False)
i_am_jc
  • 3
  • 3

1 Answers1

0

Something like this:

category_list = Category.objects.all() #Or you can filter according to your choice
for c in category_list:
  tagnames = c.tags.filter(visible=True).values("name")
  print c.name, tagnames
Arpit Agrawal
  • 882
  • 5
  • 10
  • 1
    This is "ugly", since it will do 1+N queries on your DB (where N is the number of categories selected). To avoid that do category_list = Category.objects.prefetch_related('tags'). This will do all the job in the 1st line (1 DB query), and then the for loop will only read python variables. – Ricola3D Sep 18 '13 at 06:59