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 }}
.
- How to append pages of data using jQuery and Django pagination?
- Integrating a payment gateway with Django-Oscar?
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:
Hope these can help you!
👤C.K.
- Django migrations conflict multiple leaf nodes in the migration graph
- Found another file with the destination path – where is that other file?
0👍
This will work for you without any problem in your case:
{{question.answer_name.count}}
- Django form errors prints __all__
- Django-Rest-Framework Relationships & Hyperlinked API issues
- No web processes running Django in heroku
- Save the related objects before the actual object being edited on django admin
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
- How To Find Nearest Point From User Location using geodjango?
- Why __unicode__ doesn't work but __str__ does?
Source:stackexchange.com