查找按评论最多的帖子排序的帖子:
posts = generic_annotate(Post.objects.all(), Comment, Count('comments__id')).order_by('-score', '-created')
查找按最喜欢的帖子排序的帖子:
posts = generic_annotate(Post.objects.all(), Like, Count('liking__id')).order_by('-score', '-created')
但是,我想知道如何以某种方式通过具有最多计数(评论 + 喜欢)的帖子来订购帖子,但我不确定如何继续。
现在我有:
posts = generic_annotate(Post.objects.all(), Like, Count('liking__id'), alias='like_score')
posts = generic_annotate(posts, Comment, Count('comments__id'), alias='comment_score')
And I try to use .extra to add both fields:
posts = posts.extra(select={'fieldsum':'SUM(comment_score + like_score)'}).order_by('-fieldsum', '-created')
但是我收到一条错误消息,说那些带注释的字段不存在。
class Post(models.Model):
owner = models.ForeignKey(User, related_name="")
content = models.CharField()
class Like(models.Model):
sender = models.ForeignKey(User, related_name="liking")
receiver_content_type = models.ForeignKey(ContentType)
receiver_object_id = models.PositiveIntegerField()
receiver = generic.GenericForeignKey(
ct_field="receiver_content_type",
fk_field="receiver_object_id"
)
timestamp = models.DateTimeField(default=datetime.datetime.now)
class Meta:
unique_together = (
("sender", "receiver_content_type", "receiver_object_id"),
)
def __unicode__(self):
return "%s likes %s" % (self.sender, self.receiver)
## Also has the django comments associated with it.
-----------------------------------------------------------