class Test(ModelBase):
team = models.IntegerField(null=True)
id created_at team
1 2018-02-14 10:33:46.307214+05:30 1
2 2018-02-24 10:41:40.307681+05:30 1
3 2018-03-14 12:00:02.748088+05:30 1
4 2018-03-12 18:05:33.598297+05:30 3
5 2018-03-12 18:04:00.694774+05:30 3
6 2018-04-14 11:24:48.554993+05:30 3
7 2018-04-14 11:42:27.442441+05:30 3
8 2018-05-11 15:53:21.528813+05:30 3
9 2018-05-08 15:49:58.684201+05:30 3
我们如何从当前月份的单个查询获得&团队= 3计数,上个月&团队= 3计数?
答案 0 :(得分:1)
您可以使用允许使用OR条件执行查询的Q
object:
current_month = datetime.datetime.now().month
first_day_of_current_month = datetime.datetime.now().replace(day=1)
last_month = (first_day_of_current_month - datetime.timedelta(days=1)).month
Test.objects.filter(Q(created_at__month=current_month, team=3)|Q(created_at__month=last_month, team=3))
答案 1 :(得分:1)
您可以使用链式查询集进行过滤。只需获取current_month
和last_month
(它应该是整数)和
Test.objects.filter(created_at__month__in=[current_month, last_month], team=3)
答案 2 :(得分:0)
您可以使用TruncMonth
获取每月过滤的数据。然后,您可以生成第一个和最后一个索引值。
from django.db.models.functions import TruncMonth
from django.db.models import Sum
queryset = Test.objects.all().annotate(
month=TruncMonth('created_at')).values('month').annotate(
number=Sum('team'))