在order_by()中使用Django自定义模型方法属性 [英] Using a Django custom model method property in order_by()
问题描述
我正在学习Django,我的一些模型有自定义的方法来以特定方式获取值格式。是否可以使用这些自定义方法之一的值定义为具有order_by()的模型中的属性?
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()?
这是一个示例如何实现财产。
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>]
但我无法做到:
>>> Author.objects.order_by('full_name')
FieldError: Cannot resolve keyword 'full_name' into field. Choices are: book, email, first_name, id, last_name
什么是正确的使用order_by的方法在这样的自定义属性上?
What would be the correct way to use order_by on a custom property like this?
推荐答案
不,你不能这样做。 order_by
应用于数据库级别,但数据库无法知道您的自定义Python方法。
No, you can't do that. order_by
is applied at the database level, but the database can't know anything about your custom Python methods.
您可以使用单独的字段来排序:
You can either use the separate fields to order:
Author.objects.order_by('first_name', 'last_name')
或在Python中执行排序:
or do the ordering in Python:
sorted(Author.objects.all(), key=lambda a: a.full_name)
这篇关于在order_by()中使用Django自定义模型方法属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!