【问题标题】:Django query, greater than and lower than are not workingDjango查询,大于和小于不起作用
【发布时间】:2018-02-28 13:21:56
【问题描述】:

我有下表:

class OverallAdvise(mixins.OrdMixin, mixins.EqMixin, models.Model):
    section = models.ForeignKey('quest.Section',
                                on_delete=models.CASCADE,
                                related_name='section_owner')
    range_start = models.IntegerField(blank=True, null=True)
    range_end = models.IntegerField(blank=True, null=True)
    get_advise = models.CharField(max_length=500)

然后,在序列化程序中,我尝试根据计算的分数选择get_advise。

我的查询是:

get_overall_advise = OverallAdvise.objects.filter(section_id = section_id, range_start__gte = section_overall_score, range_end__lte = section_overall_score).values("get_advise")

但它不起作用。

当我在查询中仅使用 section_id 时,它可以正常工作。

section_id=6 和 section_overall_score=8 已给出。

我需要像range_start<=6<=range_end 这样的东西。

这是我的mysql 表的一个实例:

你能帮帮我吗?

【问题讨论】:

  • 你能告诉我range_start__gte = section_overall_score, range_end__lte = section_overall_score这是什么逻辑吗?您只想根据自己的逻辑选择 8 section_overall_score。
  • @NeErAjKuMaR 我想要类似的东西:range_start<=6<=range_end
  • 但是根据你的逻辑你不会得到输出。更新代码如下range_start__lte = section_overall_score, range_end__gte = section_overall_score
  • @NeErAjKuMaR 谢谢!如果section_overall_score 在0,12 范围内,则该示例有效。如果分数更高,我仍然会出错。即使范围值存储在我的数据库中。

标签: python mysql django


【解决方案1】:

在您的 mysql 示例中,我看到 range_start 永远不会大于 range_end,因此 range_start__gte=value 和 range_end__lte=value 不会匹配任何条目,因为值是相同的。除了 range_start == range_end == value

所以如果你想要range_start <= 6 <= range_end,你应该使用range_start__lte=6, range_end__gte=6

【讨论】:

  • 当我在查询中仅使用 section_id 时,它可以正常工作。
  • 好吧,不知道这行得通。然后请查看我编辑的答案
  • 我想要类似的东西:range_start<=6<=range_end
  • 那么应该是range_start__lte=6, range_end__gte=6,因为range_start小于等于,range_end大于等于
  • 就是这样!谢谢!将其添加到您的答案中以接受它!
【解决方案2】:

当你像 if 语句一样编写 ORM 查询时,你会看到错误

for row in OverallAdvise.objects.all():
    if row.section_id == section_id:
        if range_start >= section_overall_score:
            if range_end <= section_overall_score:
                return row.get_advice

这永远不会像range_start range_end 那样成功。我认为您想在查询中切换 lte 和 gte。

get_overall_advise = OverallAdvise.objects.filter(section_id = section_id, range_start__lte = section_overall_score, range_end__gte = section_overall_score).values("get_advise")

【讨论】:

  • 这仅适用于section_overall_score = 0-12。例如,如果 section_overall_score =16 我仍然收到 http 500 错误。
  • 还有什么错误。该错误也可能与此无关。如果适用,请将错误添加到原始帖子中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-17
  • 1970-01-01
  • 2019-08-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多