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 count the total non-distinct many-to-many relationships across objects of a model?

Assume I have the following models:

class Tag(Model):
  name = CharField()

class Book(Model):
  title = CharField()
  tags = ManyToManyField(Tag)

Now suppose I have 3 books, and each book has 3 tags. Some of the tags might be the same for some of the books, it doesn’t matter.

Book 1 (Tags = "tag1", "tag2", "tag3")
Book 2 (Tags = "tag1", "tag4", "tag5")
Book 3 (Tags = "tag4", "tag5", "tag6")

How can I count all non-distinct tags in a Django ORM query so that I get 9 as a result?

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

>Solution :

You can count with:

Book.tags.through.objects.count()

This will count the number of tags for all Books. If you have a set of Books, you can count with:

Tag.objects.filter(book__in=[1, 2, 3]).count()
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