[Fixed]-Django how to get count for manytomany field

17👍

This worked:

{{question.answer_set.count}}

Happy..

👤gamer

16👍

You can do something like {{ question.answers.all.count }}, but if you are iterating over more than question it will cause a database query for every question.

If you want to annotate the whole queryset with the count for each question:

from django.db.models import Count

context['question_list'] = Question.objects.all().annotate(
    answer_count=Count('answers')
)

Then you can access the count for each question with {{ question.answer_count }}.

6👍

Why not use: Question.objects.all().count()

For my project, I have a Field in ‘Info’ Model

users_like = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="%(app_label)s_%(class)s_likes", blank=True)

I use below code to count the number of like then show it in Admin List Page.

# admin.py
from django.contrib import admin

from .models import Info
class InfoAdmin(admin.ModelAdmin):
    list_display = ('id', 'title', 'like_count',)
    def like_count(self, obj):
        return obj.users_like.all().count()

admin.site.register(Info, InfoAdmin)

The result is:
image
Hope these can help you!

👤C.K.

0👍

This will work for you without any problem in your case:

{{question.answer_name.count}}

0👍

Not entirely related to original question, but if you’re getting the count just to check if there are records, this should be much faster as the dataset grows:

if question.answers.first() is not None
👤winrid

Leave a comment