我想按日期订购这些汽车,但如果汽车有车主,车主的出生日期必须采取而不是汽车的creation_date。
这是可能吗?
解决方案看看这个类似的问题:好的排序方式查询集? - Django
您不能使用模型的Meta 排序,因为它只接受一个字段
https ://docs.djangoproject/en/dev/ref/models/options/#ordering
您不能使用查询 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
docs.djangoproject/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
发布评论