45

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?

Andre Miller
  • 15,255
  • 6
  • 55
  • 53

1 Answers1

81

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)
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • Maybe `F()` objects will work in this case. Haven't tested, but maybe ordering by `F('first_name')+' '+F('last_name')`? – Michael Mior Dec 14 '11 at 20:23
  • 1
    To sort by _multiple_ custom fields with `sorted` you can use key=attrgetter as described at https://wiki.python.org/moin/HowTo/Sorting – Chirael Mar 06 '15 at 14:19
  • 2
    For `sorted(CGHSSection.objects.all(), key=lambda a: a.modtitle)`, I get `TypeError: '<' not supported between instances of 'method' and 'method'` – Joel G Mathew Feb 24 '19 at 08:57
  • @JoelGMathew https://stackoverflow.com/a/51929973/4329778 – Stephen May 04 '21 at 20:21