Search code examples
djangodjango-modelsdjango-managers

How to filter relationship item in Django?


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)

Solution

  • 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