Home > database >  Correct way of writing a filter query on a geodjango model (finding out if a multipolygon field cont
Correct way of writing a filter query on a geodjango model (finding out if a multipolygon field cont

Time:06-12

I am new to geodjango and trying to build an application after going through the tutorial. So, I have this model:

from django.contrib.gis.db import models

class CountryBorder(models.Model):
    f_code = models.CharField(max_length=5)
    name = models.CharField(max_length=254)
    ....
    ....
    #the multipolygonfield on which I want to perform lookup
    geom = models.MultiPolygonField(srid=4326)

    def __str__(self):
        return self.name

and I am trying to find the model instance which contains (the model.geom field contains) a point. I tried doing that as described in the documentation:

from app_name.models import CountryBorder
from django.contrib.gis.geos import Point
pnt = Point(23.1827, 75.7682)
CountryBorder.objects.get(geom_contains=pnt)

But I get the following error message:

django.core.exceptions.FieldError: Cannot resolve keyword 'geom_contains' into field. Choices are: f_code, geom,name.....

Am I missing something?

CodePudding user response:

You separate the field name (here geom) and lookup (here __contains [Django-doc], with two consecutive underscores (__), not a single underscore, so:

from app_name.models import CountryBorder
from django.contrib.gis.geos import Point

pnt = Point(23.1827, 75.7682)

CountryBorder.objects.get(geom__contains=pnt)
  • Related