简体   繁体   English

如何使用两个字段作为组合字段对Django queryset进行排序

[英]How to sort django queryset with two fields as a combined field

I have a Deadline model which have two fields, start_date and end_date . 我有一个Deadline模型,其中有两个字段start_dateend_date I want to sort the queryset with both the fields but have a copy of deadline for each date 我想使用两个字段对queryset进行排序,但是每个日期都有一个截止日期的副本

I tried creating annotated common fields and ordering through that. 我尝试创建带注释的通用字段并进行排序。

class Deadline(models.Model):
    start_date = models.DateTimeField()
    end_date = models.DateTimeField

dl_start = deadline_queryset.annotate(date=F('start_date'))
dl_end = deadlien_queryset.annotate(date=F('end_date'))
dl_all = dl_start.union(dl_end).order_by('date')

I need a timeline of events. 我需要一个事件时间表。
Consider if my queryset has 2 objects: 考虑一下我的查询集是否有2个对象:

Deadline <id: 1, start_date: 12-dec, end_date: 24-jan>
Deadline <id: 2, start_date: 15-dec, end_date: 21-jan>

I need a list of deadlines like: 我需要以下截止日期清单:

Deadline <id: 1, start_date: 12-dec, end_date: 24-jan, date: 12-dec>
Deadline <id: 2, start_date: 15-dec, end_date: 21-jan, date: 15-dec>
Deadline <id: 2, start_date: 15-dec, end_date: 21-jan, date: 21-jan>
Deadline <id: 1, start_date: 12-dec, end_date: 24-jan, date: 24-jan>

In my aforementioned code, the annotated fields were not being carry forward after the union and so I was unable to use order_by on it. 在我上面提到的代码中,合并后的字段没有被结转,因此我无法在其上使用order_by。

It worked after using the following variation: 使用以下变体后,它可以工作:

dl_start = deadline_queryset.annotate(date=F('start_date')).values('id', 'start_date', 'end_date', 'date')
dl_end = deadlien_queryset.annotate(date=F('end_date')).values('id', 'start_date', 'end_date', 'date')
dl_all = dl_start.union(dl_end).order_by('date')

This helped me carry forward the annotated date field. 这有助于我推进带注释的date字段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM