python 在 order_by() 中使用 Django 自定义模型方法属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/981375/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 21:12:13  来源:igfitidea点击:

Using a Django custom model method property in order_by()

pythondjangodjango-models

提问by Andre Miller

I'm currently learning Django and some of my models have custom methods to get values formatted in a specific way. Is it possible to use the value of one of these custom methods that I've defined as a property in a model with order_by()?

我目前正在学习 Django,我的一些模型有自定义方法来获取以特定方式格式化的值。是否可以使用我在带有 order_by() 的模型中定义为属性的这些自定义方法之一的值?

Here is an example that demonstrates how the property is implemented.

这是一个演示如何实现该属性的示例。

class Author(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=40)
    email = models.EmailField(blank=True, verbose_name='e-mail')

    def _get_full_name(self):
        return u'%s %s' % (self.first_name, self.last_name)
    full_name = property(_get_full_name)

    def __unicode__(self):
        return self.full_name

With this model I can do:

有了这个模型,我可以做到:

>>> Author.objects.all()
[<Author: John Doh>, <Author: Jane Doh>, <Author: Andre Miller>]
>>> Author.objects.order_by('first_name')
[<Author: Andre Miller>, <Author: Jane Doh>, <Author: John Doh>]

But I cannot do:

但我不能这样做:

>>> Author.objects.order_by('full_name')
FieldError: Cannot resolve keyword 'full_name' into field. Choices are: book, email, first_name, id, last_name

What would be the correct way to use order_by on a custom property like this?

在这样的自定义属性上使用 order_by 的正确方法是什么?

回答by Daniel Roseman

No, you can't do that. order_byis applied at the database level, but the database can't know anything about your custom Python methods.

不,你不能那样做。order_by应用于数据库级别,但数据库无法了解有关您的自定义 Python 方法的任何信息。

You can either use the separate fields to order:

您可以使用单独的字段来订购:

Author.objects.order_by('first_name', 'last_name')

or do the ordering in Python:

或在 Python 中进行排序:

sorted(Author.objects.all(), key=lambda a: a.full_name)