【问题标题】:SQL comparison functions/operators on DjangoDjango 上的 SQL 比较函数/运算符
【发布时间】:2013-07-09 23:04:01
【问题描述】:

我需要在 Django 模型上运行以下查询:

SELECT *
FROM app_model
WHERE GREATEST(field1, fixed_value) < LEAST(field2, another_fixed_value)

有什么方法可以让我在不使用 raw() 方法的情况下运行这个查询?

【问题讨论】:

    标签: sql django django-models


    【解决方案1】:

    您至少可以通过使用extra 避免raw。我认为 ORM 不会以其他方式暴露 GREATESTLEAST

    理论上,您可以将约束分解为不同的可能性,然后or 将它们组合在一起:

    mymodel.objects.filter(Q(field1__gt=fixed_value and field2__lt=another_fixed_value and field1__lt=field2) | \
                           Q(field1__lte=fixed_value and field2__lt=another_fixed_value and field2__gt=fixed_value) | \
                           Q(field1__gt=fixed_value and field2__gte=another_fixed_value and field1__lt=another_fixed_value) | \
                           Q(field1__lte=fixed_value and field2__gte=another_fixed_value and fixed_value < another_fixed_value))
    

    除非很明显,您实际上不会包含 and fixed_value &lt; another_fixed_value。如果它们实际上是固定的并且您在编写代码时知道它们,则只需进行前两次比较 - 如果您不知道它们,则仅构建最后一个 Q 对象,或在必要时将其构建到查询中。

    也就是说,这太可怕了,我认为extra 是一个更好的选择。

    mymodel.objects.extra(where=['GREATEST(field1, fixed_value) < LEAST(field2, another_fixed_value)'])
    

    【讨论】:

    • 谢谢! extra() 方法是我需要的! :)
    【解决方案2】:

    看看field lookups

       Model.objects.filter(id__gt=4)
    

    相当于:

    SELECT ... WHERE id > 4;
    

    小于

    Model.objects.filter(id__lt=4)
    

    相当于:

    SELECT ... WHERE id < 4;
    

    【讨论】:

      猜你喜欢
      • 2021-09-09
      • 2020-09-24
      • 1970-01-01
      • 2021-06-10
      • 2016-12-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多