django-按查询排序
我有一个名为django-按查询排序,django,django-models,Django,Django Models,我有一个名为Post的模型,它有两个字段upvoces和downvoces。现在,向上投票,向下投票都是ManyToManyField给用户。这就是模型: class Post(models.Model): profile = models.ForeignKey(Profile, on_delete=models.CASCADE) title = models.CharField(max_length=300) content = models.CharField(max
Post
的模型,它有两个字段upvoces
和downvoces
。现在,向上投票
,向下投票
都是ManyToManyField
给用户
。这就是模型:
class Post(models.Model):
profile = models.ForeignKey(Profile, on_delete=models.CASCADE)
title = models.CharField(max_length=300)
content = models.CharField(max_length=1000)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
subreddit = models.ForeignKey(Subreddit, on_delete=models.CASCADE)
upvotes = models.ManyToManyField(Profile, blank=True, related_name='upvoted_posts')
downvotes = models.ManyToManyField(Profile, blank=True, related_name='downvoted_posts')
我必须在哪里查询所有帖子的排序
总计(Up票
)-总计(Down票
)
我已经尝试了Post.objects.order_by(Count('upvoates'))
开始,但出现了一个错误。请先使用
annotate()
的另一个好处是,queryset中的每一篇文章都会获得total\u voces
属性,您以后可以访问该属性,而无需额外的数据库查询或计算
Post.objects.annotate(
total_votes=Count('upvotes')-Count('downvotes')
).order_by('total_votes')