pythondjangodjango-querysetmanytomanyfield

How to unite second level ManyToManyFields?


I have models as follows:

class Tag(models.Model):
    name = models.CharField(max_length=50)

class Element(models.Model):
    tags = models.ManyToManyField('Tag')

class Category(models.Model):
    elements = models.ManyToManyField('Element')

    @property
    def tags(self):
        ...  # how can I do this?

How can I get the union of all the tags that appear in elements of a given category?

I could do something like this:

def tags(self):
    all_tags = Tag.objects.none()
    for element in self.elements.all():
        all_tags = all_tags | element.tags.all()
    return all_tags.distinct()

But is there a way to do this directly at database level?


Solution

  • Use the double underscore notation to traverse relations:

    def tags(self):
        return Tag.objects.filter(element__category=self)