Django查询,大于和低于不工作

时间:2018-02-28 13:21:57

标签: python mysql django

我有下表:

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=6section_overall_score=8

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

这是我的mysql表格的一个实例:enter image description here

你能帮我吗?

2 个答案:

答案 0 :(得分:1)

在您的mysql示例中,我发现range_start绝不会大于range_end,因此range_start__gte=valuerange_end__lte=value不会匹配任何条目,因为值相同。除了range_start == range_end == value

之外

因此,如果您需要range_start <= 6 <= range_end,请使用range_start__lte=6, range_end__gte=6

答案 1 :(得分:0)

当您将ORM查询编写为if语句时,您将看到错误

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&lt; = range_end永远不会成功。我想您想在查询中切换ltegte

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