views:

625

answers:

1

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?

+8  A: 

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