Django的ORM在翻译Between and的时候怎么解决冲突?

ponponon
  • 46
from django.db import models

class Teacher(models.Model):
    name = models.CharField(max_length=200)
    email = models.CharField(max_length=200)
    age = models.IntegerField()
    country = models.CharField(max_length=100)
In [1]: from teachers.models import Teacher

In [5]: Teacher.objects.filter(age__range=[1,5]).exclude(country='UK')
Out[5]: (0.016) SELECT `teachers_teacher`.`id`, `teachers_teacher`.`name`, `teachers_teacher`.`email`, `teachers_teacher`.`age`, `teachers_teacher`.`country` FROM `teachers_teacher` WHERE (`teachers_teacher`.`age` BETWEEN 1 AND 5 AND NOT (`teachers_teacher`.`country` = 'UK')) LIMIT 21; args=(1, 5, 'UK')
<QuerySet []>

BETWEEN AND 和 and 运算符冲突了,怎么办?

ORM翻译的结果

SELECT *
FROM `teachers_teacher`
WHERE `teachers_teacher`.`age` BETWEEN 1 AND 5
    AND NOT `teachers_teacher`.`country` = 'UK';

正确的样子

SELECT *
FROM `teachers_teacher`
WHERE (`teachers_teacher`.`age` BETWEEN 1 AND 5)
    AND (NOT `teachers_teacher`.`country` = 'UK');

怎么才能让ORM加括号?

回复
阅读 176
1 个回答

程序这里sql解析between and不会冲突,结果是一样的,只是人看着容易有点误解。

你知道吗?

宣传栏