简体   繁体   English

django order_by值未存储在数据库中

[英]django order_by value not stored in database

I have a model, Rating , which looks something like this: 我有一个Rating模型,看起来像这样:

class Rating(models.Model):
    upvotes = models.IntegerField(default=0)
    downvotes = models.IntegerField(default=0)
    @property
    def total(self):
        return self.upvotes - self.downvotes

I have a group of ratings which I need to order by their total property. 我有一组等级,需要按它们的total资产进行排序。 As you can see, it is not a value stored in the database. 如您所见,它不是存储在数据库中的值。 rating_set.order_by("total") does not work. rating_set.order_by("total")不起作用。

I could use Python's sorted function on the list of ratings, with key=lambda r: r.total . 我可以在等级列表上使用Python的sorted函数,并使用key=lambda r: r.total But this seems to me that it would be rather inefficient and there probably exists a better way from within Django. 但这在我看来似乎效率很低,并且在Django内部可能存在更好的方法。

Does Django support ordering by derived values? Django是否支持按派生值排序? Would I improve performance by making total a value stored in the database? 我是否可以通过将total值存储在数据库中来提高性能?

This is because the database has no idea about the total property. 这是因为数据库不知道total属性。 It only exists in python. 它仅存在于python中。 You can replicate the same behavior by using extra to have it calculated and sorted by the database. 您可以通过使用extra来复制相同的行为,以使其按数据库进行计算和排序。 Like so: 像这样:

Rating.objects.extra(select={'total': "upvotes - downvotes"}).order_by('-total')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM