在 order_by() 中使用 Django 自定义模型方法属性 [英] Using a Django custom model method property in order_by()
问题描述
我目前正在学习 Django,我的一些模型有自定义方法来获取以特定方式格式化的值.是否可以使用我在带有 order_by() 的模型中定义为属性的这些自定义方法之一的值?
这是一个演示如何实现属性的示例.
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):返回 u'%s %s' % (self.first_name, self.last_name)full_name = 属性(_get_full_name)def __unicode__(self):返回 self.full_name
有了这个模型,我可以做到:
<预><代码>>>>Author.objects.all()[<作者:John Doh>,<作者:Jane Doh>,<作者:Andre Miller>]>>>Author.objects.order_by('first_name')[<作者:安德烈米勒>,<作者:简多>,<作者:约翰多>]但我做不到:
<预><代码>>>>Author.objects.order_by('full_name')FieldError:无法将关键字full_name"解析为字段.选项有:book、email、first_name、id、last_name在这样的自定义属性上使用 order_by 的正确方法是什么?
不,你不能那样做.order_by
应用于数据库级别,但数据库无法了解有关您的自定义 Python 方法的任何信息.
您可以使用单独的字段进行排序:
Author.objects.order_by('first_name', 'last_name')
或者在 Python 中进行排序:
sorted(Author.objects.all(), key=lambda a: a.full_name)
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>]
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?
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')
or do the ordering in Python:
sorted(Author.objects.all(), key=lambda a: a.full_name)
这篇关于在 order_by() 中使用 Django 自定义模型方法属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!