【问题标题】:Using a Django custom model method property in order_by()在 order_by() 中使用 Django 自定义模型方法属性
【发布时间】:2010-11-02 03:43:40
【问题描述】:

我目前正在学习 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):
        return u'%s %s' % (self.first_name, self.last_name)
    full_name = property(_get_full_name)

    def __unicode__(self):
        return self.full_name

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

>>> 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 的正确方法是什么?

【问题讨论】:

    标签: python django django-models


    【解决方案1】:

    不,你不能那样做。 order_by 应用于数据库级别,但数据库对您的自定义 Python 方法一无所知。

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

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

    或在 Python 中进行排序:

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

    【讨论】:

    • 也许F() 对象可以在这种情况下工作。尚未测试,但可能通过F('first_name')+' '+F('last_name') 订购?
    • 要使用sorted多个自定义字段排序,您可以使用wiki.python.org/moin/HowTo/Sorting中所述的key=attrgetter
    • 对于sorted(CGHSSection.objects.all(), key=lambda a: a.modtitle),我得到TypeError: '&lt;' not supported between instances of 'method' and 'method'
    猜你喜欢
    • 2011-11-28
    • 1970-01-01
    • 1970-01-01
    • 2022-01-24
    • 1970-01-01
    • 2013-04-18
    • 2016-04-06
    • 1970-01-01
    • 2022-10-15
    相关资源
    最近更新 更多