I have a Deadline
model which have two fields, start_date
and end_date
. I want to sort the queryset with both the fields but have a copy of deadline for each date
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:
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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.