django how to get count for manytomany field

This worked:

{{question.answer_set.count}}

Happy..


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 }}.


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!