Fetch and count all records in M2M join table

I have two tables that are in M2M relationship. I have not created explicit model for the join table.

class CustomUser(AbstractUser):
    class Meta:
        app_label = "users"
        db_table = "users"
class Listing(models.Model):
    bookmarks = models.ManyToManyField(CustomUser, related_name="bookmarked_listings", blank=True)

    class Meta:
        app_label = "listings"
        db_table = "listings"

How can I fetch and count all records in the join table, listing_bookmarks? I don't mean just getting bookmarks of a listing or bookmarked listings of an user.

Use the ManyToManyField through model option on your bookmarks:

  • fetch all records: bookmarks.through.objects.all()
  • count all records: bookmarks.through.objects.count()

See Django docs: https://docs.djangoproject.com/en/5.1/ref/models/fields/#django.db.models.ManyToManyField.through

You can access the auto-generated join table directly through the field's intermediate model via the .through attribute.

For your case:

total_bookmarks = Listing.bookmarks.through.objects.count()
Вернуться на верх