How to filter Longitude/Latitude on Django PointField directly?

I want to filter directly on a lat/lng value on a GeoDjango PointField.

e.g. geolocation__lat__lte=40.0

Typically in django i can access Latitude/Longitude directly like geolocation.x or geolocation.y so i tried to filter like geolocation_y__lte=40.0.

FieldError: Unsupported lookup 'y' for PointField or join on the field not permitted. was the result.

ChatGPT wasn't able to help out and I don't find a related question here on stackoverflow.

Will be thankful for any help.

You can work with the ST_X [postgis.net] and ST_Y [postgis.net] functions that are provided by the database, these however are not implemented directly in Django as far as I know, but that is not a problem: we can define these ourselves.

from django.db.models import FloatField
from django.db.models.expressions import Func


class ST_X(Func):
    function = 'ST_X'
    output_field = FloatField()


class ST_Y(Func):
    function = 'ST_Y'
    output_field = FloatField()

and then work with:

MyModel.objects.alias(
    geolocation_lat=ST_Y('geolocation'), geolocation_long=ST_X('geolocation')
).filter(geolocation_lat__lte=40.0)
Back to Top