Django:过滤(“纬度,经度”)字段
我将纬度和经度存储为类似(“纬度,经度”)的charfield。我更喜欢保持这种状态。
我需要过滤结果以仅显示纬度 > w,纬度< x,经度> y,经度< z。
在不改变存储经纬度的方式的情况下如何做到这一点?
I am storing the the latitude and longitude as a charfield like ("latitude, longitude"). I prefer to keep it this way.
I need to filter the results to show only latitude > w, latitude < x, longitude > y, longitude < z.
How can I do this without change how I store the lat,long?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Django ORM 无法帮助您过滤该字段。您的架构未针对您尝试的查询类型正确设计。
我的建议:
修改您的架构以首先使用单独的数字列。 (我知道您正在专门寻找一种可以避免这种情况的选项,但这仍然是正确的解决方案)。
添加两个新的数字列,并在模型发生更改时更新/设置这些列。您还需要进行一次性批量更新来设置所有现有行的初始值。
您可以设置一个自定义 SQL 查询,该查询将遍历每一行并拆分列以检索纬度和经度的单独数值并对其进行过滤。在这种情况下,您几乎绕过了 ORM 并自己直接进入 SQL,并且需要使用数据库上可用的任何拆分方法(自定义拆分函数、正则表达式等)。查询会很慢。
向您的模型添加一个方法,该方法将在 Python 中拆分字符串并返回数字数据。要使用此数据进行任何类型的过滤,您需要从数据库中提取所有模型(昂贵)并在内存中进行过滤(速度很快,但您失去了 SQL 和/或 ORM 的优势)。此选项可能无法很好地扩展。
祝你好运...
The Django ORM isn't going to be able to help you filter on that field. Your schema isn't designed properly for the type of query you're attempting.
My suggestions:
Modify your schema to use separate numeric columns to begin with. (I know you are specifically looking for an option that avoids this but it's still the proper solution).
Add two new numeric columns and have those columns updated/set whenever a change is made to the model. You would also need to do a one-time mass update to set the initial values for all of the existing rows.
You may be able a rig up a custom SQL query that will go through each row and split the column to retrieve the separate numeric values for latitude and longitude and filter on them. In this case you're pretty much bypassing the ORM and going directly to SQL by yourself and will need to use whatever split methods are available on your database (custom split function, regex, etc). The query will be slow.
Add a method to your model that will split the string in Python and return the numeric data. To do any kind of filtering use this data you will need to pull all of the models from your database (expensive) and do the filtering in memory (fast but you lose the advantages of SQL and/or the ORM). This option probably won't scale very well.
Good luck...
正如其中一位评论者提到的,您绝对应该查看 Geodjango,它提供本地地理信息支持。从他们的页面来看:GeoDjango 是 Django 的一个附加组件,可将其转变为世界一流的地理 Web 框架。 GeoDjango 致力于尽可能简单地创建地理 Web 应用程序,例如基于位置的服务。一些功能包括:
As one of the commenters mentioned, you should definitely look at Geodjango, which offers native geo-information support. From their page: GeoDjango is an add-on for Django that turns it into a world-class geographic web framework. GeoDjango strives to make at as simple as possible to create geographic web applications, like location-based services. Some features include: