本文介绍了Django得到每个帖子的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个模型,Post和Vote。用户可以upvote和downvote帖子。models.py:
c $ c> >I have two models, Post and Vote. Users can upvote and downvote posts.
models.py:
class Post(models.Model): poster = models.ForeignKey('auth.User') question = models.ForeignKey('self', null=True, blank=True) post_title = models.CharField(max_length=300) post_content = models.TextField(null=True, blank=True) is_published = models.BooleanField(default=True) is_locked = models.BooleanField(default=False) is_question = models.BooleanField(default=True) is_deleted = models.BooleanField(default=False) created_date = models.DateTimeField( default=timezone.now) published_date = models.DateTimeField( blank=True, null=True) date_modified = models.DateTimeField( blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.post_title class Vote(models.Model): user = models.ForeignKey('auth.User') post = models.ForeignKey('Post') vote_type = models.SmallIntegerField()#-1, 0, 1 date_voted = models.DateTimeField( default=timezone.now) def __str__(self): return self.userI use the following code in my view to return the posts to templates:
views.py:
def index(request): posts = Post.objects.filter(created_date__lte=timezone.now( ), is_question=1, is_published=1).order_by('-created_date') #removed the paging stuff here for simplification return render(request, 'homepage/index.html', {'posts': posts})This just returns the posts, but I also want the sum of the vote_type column for each post which is the total number of votes for the post.
Currently I use template tags for each post to check for each post's votes.
My index.html sample code:
{% for post in posts %} {{ post|total_votes|default:"0" }} {% endfor %}Is there any way to query everything in the views.py and then in the template I could check like this: {{post.total_votes}}?
解决方案Yeah, you can use annnotate. Generally, it would look something like
from django.db.models import Sum posts = Post.objects.filter(...).annotate(total_votes=Sum('vote__vote_type'))each post object in posts will then have a total_votes attribute.
这篇关于Django得到每个帖子的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!