Django自定义order

编程入门 行业动态 更新时间:2024-10-28 04:21:16
本文介绍了Django自定义order_by的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我有一个模型,例如。汽车用外键,例如所有者,可能是也可能不是空白的。 汽车有一个creation_date。

我想按日期订购这些汽车,但如果汽车有车主,车主的出生日期必须采取而不是汽车的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

本文发布于:2023-10-15 01:30:56,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1492841.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:自定义   Django   order

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!