简体   繁体   English

如何使模型中的函数像字段一样起作用?

[英]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.

相关问题 如何使属性函数像数据库中的真实字段一样工作 - how to make a property function to act like a real field in the database 如何使 function 的参数像变量字符串方法一样 - How to make parameter of function act like variable string methods kivy:如何使图像像按钮一样 - kivy: how to make an image act like a button function 如何像描述符一样工作? - How Can a function act like a descriptor? 使绑定方法像函数一样运行的最pythonic方法是什么? - What is the most pythonic way to make a bound method act like a function? 如何使熊猫get_dummies像DictVectorizer一样工作 - How to make pandas get_dummies to act like DictVectorizer 如何使gnome-terminal命令像python中的对象一样工作 - How to make gnome-terminal command act like object in python 如何使类在查找方法中表现得像超级 - How to make class act like super in find method In Python, make a variable act like a function, call a function without parentheses, alias a function as a variable, etc? - In Python, make a variable act like a function, call a function without parentheses, alias a function as a variable, etc? 如何在model-2的序列化器中使用与model-2实例相关的model-1实例的url创建一个字段? - How to make a field with urls of model-1 instances that are related to model-2 instance inside the serializer of model-2?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM