【问题标题】:How can I make this query in Django?如何在 Django 中进行此查询?
【发布时间】:2019-12-10 06:45:56
【问题描述】:

我有这些字段(test_type, status, begin_time, and_time)。status 字段具有三种状态(012)。 我想在哪里做一个查询集:

(test_type = 'difficult') and 
(if status=1 and begin_time + 2x(end_time - begin_time) < timezone.now()) or
(if status=2 and end_time < timezone.now()) 

然后选择这些字段。如果状态 state=0 我不想选择该字段。 如何使用 Django ORM 制作这个查询集?

【问题讨论】:

  • status==1 和 status==2 返回 False。 test_type = 'difficult') 没有打开的括号和 = 而不是 ==。你能检查一下你的表情吗?
  • 我已将 And 改正为 OR
  • 你能分享你的模型吗?

标签: python django django-queryset


【解决方案1】:

你将不得不在 Django 中使用 Q 对象,

Model.objects.filter((Q(status=1) & Q(begin_time < computed_value_here)) | (Q(status=2) & Q(end_time < computed_value_here)), test_type='difficult')

【讨论】:

    【解决方案2】:

    类似下面的东西应该可以工作。您需要为“twice_end_time”创建注释,因为 Django 不支持过滤器中的这种计算

    Model.objects.annotate(
        twice_end_time=F('begin_time') + 2 * F('end_time') - F('begin_time')
    ).filter(
        Q(test_type='difficult') &
        Q(status=1, twice_end_time__lt=timezone.now()) |
        Q(status=2, end_time__lt=timezone.now())
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-05-09
      • 1970-01-01
      • 2020-05-21
      • 2010-10-07
      • 2010-10-13
      • 1970-01-01
      相关资源
      最近更新 更多