Using a Django custom model method property in order_by()

前端 未结 1 803
轻奢々
轻奢々 2020-11-27 16:53

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 me

相关标签:
1条回答
  • 2020-11-27 17:39

    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)
    
    0 讨论(0)
提交回复
热议问题