Search code examples
mysqlsqldjangodjango-modelsdjango-database

How can I select two ranges of the same field in Django?


With the following model:

class Event(models.Model):
    latitude = models.FloatField()
    longitude = models.FloatField()

I would like to execute the following logic:

Select all events where latitude is in range(float1, float2) or in range (float3, float4)

This looks like this in SQL:

SELECT * FROM event WHERE latitude (BETWEEN float1 and float2) or latitude (BETWEEN float3 and float4);

I tried this in Django but I get a "SyntaxError: keyword argument repeated":

Events.objects.filter(latitude__range=(float1, float2), latitude__range=(float3, float4)

Solution

  • using Q()|Q()

    from django.db.models import Q
    Event.objects.filter(
        Q(latitude__range=(float1,float2)) | Q(latitude__range=(float3,float4))
    )
    

    see the document https://docs.djangoproject.com/zh-hans/2.2/topics/db/queries/#complex-lookups-with-q-objects