使用以下型号:
class Event(models.Model):
latitude = models.FloatField()
longitude = models.FloatField()
我想执行以下逻辑:
选择所有纬度在范围(float1,float2)或范围(float3,float4)中的事件
在SQL中看起来像这样:
SELECT * FROM event WHERE latitude (BETWEEN float1 and float2) or latitude (BETWEEN float3 and float4);
我在Django中尝试过此方法,但收到“ SyntaxError:重复的关键字参数”:
Events.objects.filter(latitude__range=(float1, float2), latitude__range=(float3, float4)
SELECT *
FROM event
WHERE (latitude BETWEEN float1 AND float2)
OR (latitude BETWEEN float3 AND float4);```
fieldName
value1之间的AND
value2是唯一的语法。实际上,您不需要添加括号:SELECT * FROM event
WHERE latitude BETWEEN float1 and float2 OR
latitude BETWEEN float3 and float4;
如果要添加括号以提高可读性,则可以添加以下内容:
SELECT * FROM event WHERE (latitude BETWEEN float1 and float2) OR (latitude BETWEEN float3 and float4);
from django.db.models import Q
Event.objects.filter(
Q(latitude__range=(float1,float2)) | Q(latitude__range=(float3,float4))
)
请参见文档https://docs.djangoproject.com/zh-hans/2.2/topics/db/queries/#complex-lookups-with-q-objects