Django:从两个模型字段过滤Queryset [英] Django: Filtering Queryset From Two Model Fields

查看:194
本文介绍了Django:从两个模型字段过滤Queryset的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的模型有两个字段(经度和纬度),我想合并成一个点对象。然而,我不知道如何基于这些值的组合进行过滤:



例如:

 >>> 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:无法将关键字pnt解析为字段。 ##我没有一个名为pnt的模型字段

我意识到这不是正确的方法,但是我认为它说明了我有的问题。如何将两个模型字段( lat + lon )合并为一个 Point 对象,然后基于该点过滤? / p>




编辑:添加事物模型

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


解决方案

最简单的方法就是@karthikr在你的问题的评论中说过, p>

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

另外,我不知道数据库有多少回旋余地,但是也可以分别存储点你的Thing对象,然后把Thing对象连接到一个Point?

psuedocode:

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

否则,我不认为有办法做你所要求的。

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

解决方案

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.

这篇关于Django:从两个模型字段过滤Queryset的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆