Reputation: 9134
I have some models that look like this:
class UserProfile(models.Model):
user = models.OneToOneField(User)
favorite_books = models.ManyToManyField(Book)
# ...
class Book(models.Model):
title = models.CharField(max_length=255)
How can I tell how many times a Book
has been favorited?
Upvotes: 1
Views: 52
Reputation: 92569
You can query the "through" table directly with the ORM:
UserProfile.favorite_books.through.objects.filter(book_id=book.id).count()
Upvotes: 3
Reputation: 50185
You'll need to replace appname_*
with the name of the M2M table in your DB, but you can do something like this:
from django.db import connections
cursor = connections['default'].cursor()
cursor.execute("""
SELECT count(*) FROM appname_userprofile_books
WHERE book_id = {book_id};
""".format(book_id=book_id))
favorited_count_list = cursor.fetchall()
You can then pull the number from favorited_count_list
.
Upvotes: 0