Home > Software design >  How to count the total non-distinct many-to-many relationships across objects of a model?
How to count the total non-distinct many-to-many relationships across objects of a model?

Time:06-30

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?

CodePudding user response:

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()
  • Related