Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading