Domanda

My model has two fields (latitude and longitude) that I want to combine to form a point object. However, I cannot figure out how to filter based on a combination of those values:

For example:

>>> from django.contrib.gis.geos import Point
>>> lat = 5
>>> lon = 1
>>> pnt = Point(lat, lon)
>>> buf = pnt.buffer(0.0001)
>>> z = Thing.objects.filter(pnt__intersects=buf) 

FieldError: Cannot resolve keyword 'pnt' into field.   ## I dont have a model field named pnt

I realize this is not the right approach, but I think it illustrates the problem that I am having. How can I combine two model fields — lat + lon — into a Point object then filter based on that point?


EDIT: adding thing model

class Thing(models.Model):
    lat = models.FloatField()
    lon = models.FloatField()
È stato utile?

Soluzione

The most straightforward way to do this is as @karthikr has said in the comments to your question, just AND the two:

z = Thing.objects.filter(lat=pnt.get_x(), lng = pnt.get_y())

Alternatively, I don't know how much leeway you have in the database, but you could also store the points separately from your Thing object, and then just link the Thing object to a Point?

psuedocode:

class Thing(models.Model):
   point = models.ForeignKey('Point')

class Point(models.Model):
   lat = models.FloatField()
   lon = models.FloatField()


z = Thing.objects.filter(point = Point.objects.get(lat, long))

Otherwise, I don't think there's a way to do what you're asking.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top