Joe Mornin
Joe Mornin

Reputation: 9134

Get number of times an object is referenced in a ManyToManyField

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

Answers (2)

jdi
jdi

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

mVChr
mVChr

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

Related Questions