簡體   English   中英

Django 多查詢

[英]Django Multiple Queries

我正在使用大量查詢來查找指定日期間隔(例如過去 7 天、過去 6 個月等)的多條記錄中字段[ft_day, ft_night]的總和。

這需要在模板中顯示上述日期間隔的總時間摘要。

ft_total 是模型中的一個屬性

有沒有更有效的方法來做到這一點? 在這里並不是真的堅持 DRY。

謝謝你的幫助。

views.py get_context_data()

## shortened ##
context['last_6_months_rpic'] = RPLogbookEntry.objects.filter(user=self.request.user, user_role='RPIC', entry_date__range=(datetime.datetime(int(self.date_now.year - (self.date_now.month - 5)/12), (self.date_now.month - 6) % 12 - 1, self.date_now.day), self.date_now)
).annotate(ft_total = F('ft_day') + F('ft_night')).aggregate(Sum('ft_total'))
context['last_12_months_rpic'] = RPLogbookEntry.objects.filter(user=self.request.user, user_role='RPIC', entry_date__range=(datetime.datetime(int(self.date_now.year - (self.date_now.month - 12)/12), (self.date_now.month - 12) % 12 - 1, self.date_now.day), self.date_now)
).annotate(ft_total = F('ft_day') + F('ft_night')).aggregate(Sum('ft_total'))

您可以將過濾器傳遞給Sum ,這允許您在同一聚合中使用不同的過濾器進行多個求和

RPLogbookEntry.objects.filter(
    user=self.request.user,
    user_role='RPIC',
).annotate(
    ft_total=F('ft_day') + F('ft_night')
).aggregate(
    last_6_months_rpic=Sum('ft_total', filter=Q(entry_date__range=(datetime.datetime(int(self.date_now.year - (self.date_now.month - 5)/12), (self.date_now.month - 6) % 12 - 1, self.date_now.day), self.date_now))),
    last_12_months_rpic=Sum('ft_total', filter=Q(entry_date__range=(datetime.datetime(int(self.date_now.year - (self.date_now.month - 12)/12), (self.date_now.month - 12) % 12 - 1, self.date_now.day), self.date_now))),
)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM