Django: Filtering Queryset From Two Model Fields

拜拜、爱过 提交于 2019-12-08 13:37:46

问题


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()

回答1:


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.



来源:https://stackoverflow.com/questions/19167076/django-filtering-queryset-from-two-model-fields

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!