【问题标题】:How do we get multiple values from a single django orm query?我们如何从单个 django orm 查询中获取多个值?
【发布时间】:2018-06-01 06:27:52
【问题描述】:
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 个计数?

【问题讨论】:

  • 你可以发布模型课吗?
  • 当然我会添加模型类。

标签: django postgresql django-orm


【解决方案1】:

您可以使用Q object,它允许使用 OR 条件执行查询:

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))

【讨论】:

  • 我们可以从这个查询中得到每个月的数据吗?
  • 通过上面的查询,我们一起过滤。但是我们可以从一个查询中为 current_month、last_month 执行此操作吗?
  • @BharatBittu 您可以添加order_by('created_at') 这将按日期对输出进行排序。
  • 没关系 :) 非常感谢 :)
  • 类似docs.djangoproject.com/en/2.0/topics/db/aggregation pubs = Publisher.objects.annotate(below_5=below_5).annotate(above_5=above_5)
【解决方案2】:

您可以使用链查询集进行过滤。只要得到你的current_monthlast_month(它应该是整数)和

Test.objects.filter(created_at__month__in=[current_month, last_month], team=3)

【讨论】:

  • 运行此查询后,我们如何获得每个月的数据?
  • 就像@neverwalkaloner 一样使用
  • 您不需要链接,只需将两个条件放在一个调用中即可。
【解决方案3】:

您可以使用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'))

【讨论】:

  • 不,我想要这个月的输出,团队 3 的总人数是 5
猜你喜欢
  • 2018-12-22
  • 1970-01-01
  • 2020-01-27
  • 1970-01-01
  • 1970-01-01
  • 2021-06-10
  • 2017-09-09
  • 1970-01-01
  • 2020-11-11
相关资源
最近更新 更多