问题描述
我有一个模型,例如。汽车用外键,例如所有者,可能是也可能不是空白的。汽车有一个creation_date。
我想按日期订购这些汽车,但如果汽车有车主,车主的出生日期必须采取而不是汽车的creation_date。
这是可能吗?
看看这个类似的问题:
您不能使用模型的Meta 排序
,因为它只接受一个字段
您不能使用查询 order_by('creation_date','birthdate')
,因为它只能按birthdate排序,如果他们有相同的 creation_date
所以,您可以编写一个自定义管理器来为您整合一个自定义排序。
import operator
class CarManager(models.Manager):
def get_query_set(self):
auths = super(CarManager,self).get_query_set()。all()。order_by(' - creation')
ordered = sorted(auths,key = operator.attrgetter('birthday'))
返回订单
class Car(models.Model):
sorted = CarManager()
所以现在你可以查询:
Car.sorted.all()
获取所有排序车的查询
I've got a model eg. Car with a foreign key eg. Owner, which may or may not be blank.The Car has a creation_date.
I would like to order these cars by date, but if the car has an owner, the date of birth of the owner must be taken instead of the creation_date of the car.
Is this possible?
解决方案 Have a look at this similar question: Good ways to sort a queryset? - Django
You can't use the model's Meta ordering
as it only accepts one field
https://docs.djangoproject.com/en/dev/ref/models/options/#ordering
You can't use the query order_by('creation_date', 'birthdate')
as it only sorts by birthdate if they have the same creation_date
So, you could write a custom manager to do incorporate a custom sort for you.
import operator
class CarManager(models.Manager):
def get_query_set(self):
auths = super(CarManager, self).get_query_set().all().order_by('-creation')
ordered = sorted(auths, key=operator.attrgetter('birthday'))
return ordered
class Car(models.Model):
sorted = CarManager()
so now you can query:
Car.sorted.all()
to get all a queryset of sorted car's
这篇关于Django自定义order_by的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!