问题
I have model for question:
class Question(models.Model):
user = models.ForeignKey(User)
title = models.CharField(max_length=120)
description = models.TextField()
answers = models.ManyToManyField('Answer',related_name='answer_name', blank=True)
post_date = models.DateTimeField(auto_now=True)
def __unicode__(self):
return self.title
And I have model for answer:
class Answer(models.Model):
user = models.ForeignKey(User)
question = models.ForeignKey(Question)
ans_body = models.TextField()
post_date = models.DateTimeField(auto_now=True)
def __unicode__(self):
return self.ans_body
Question creation and answer submission are working perfectly. I cant correctly show answer for particular question. But when I try to get the count of answer for particular question its not showing. It displays 0 count.
In my view I am getting the list of the answer by:
context["question_list"] = Question.objects.all()
And in my template
{% for question in question_list %}
{{ question.title }}
Ans:{{question.answers.count}}
{% endfor %}
When I do this I get the count 0 if there are answers. How can I get the count of the answers for particular questions.
回答1:
This worked:
{{question.answer_set.count}}
Happy..
回答2:
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 }}
.
回答3:
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(obj):
return obj.users_like.all().count()
admin.site.register(Info, InfoAdmin)
The result is:

来源:https://stackoverflow.com/questions/27149984/django-how-to-get-count-for-manytomany-field