[英]How to make a function inside a model act like a field?
I have a Post
model that links wth PostScore
through ForeignKey: 我有一个
Post
模型, PostScore
通过ForeignKey链接到PostScore
:
class Post(models.Model):
user = models.ForeignKey(User, blank=True, null=True)
title = models.TextField(max_length=76)
...
class PostScore(models.Model):
user = models.ForeignKey(User, blank=True, null=True)
post = models.ForeignKey(Post, related_name='score')
upvotes = models.IntegerField(default=0)
downvotes = models.IntegerField(default=0)
def trending(self):
score = self.upvotes - self.downvotes
return score
So when I try to sort my Posts like this: 因此,当我尝试按以下方式对我的帖子进行排序时:
posts = Post.objects.all().order_by('-score__upvotes')
It works fine but how would I be able to sort by trending
?: 它工作正常,但如何按
trending
排序?:
posts = Post.objects.all().order_by('-score__trending')
the above code creates this error: 上面的代码创建此错误:
FieldError at /news/
Cannot resolve keyword 'trending' into field. Choices are: downvotes, id, post, post_id, upvotes, user, user_id
使用注释方法计算得分差异,然后使用该计算字段排序。
Post.objects.annotate(score_diff=F('upvotes') - F('downvotes')).order_by('-score_diff')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.