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?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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)
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0