简体   繁体   English

SQLAlchemy 计算列和排序

[英]SQLAlchemy calculated column and sort

I want to calculate the distance from the input zip code and the zip code stored in the database and sort them in order of distance.我想计算输入邮政编码和存储在数据库中的邮政编码的距离,并按距离顺序对它们进行排序。

I have a 'getdistance' function that calculates the distance from two zip codes using pgeocode.我有一个“getdistance”函数,它使用 pgeocode 计算两个邮政编码的距离。 I would like to implement the following我想实现以下

neighbor = database.query(DataBase).order_by(getdistance(input_zipcode, Database.zipcode))

Is this possible using sqlalchemy?这可能使用 sqlalchemy 吗?

It is not possible if you are using a db engine like MySQL or PostgreSQL, as the order_by feature is used to build a SQL statement run by the database engine which would have no ability to use the pgeocode python library.如果您使用的是 MySQL 或 PostgreSQL 等数据库引擎,这是不可能的,因为order_by功能用于构建由无法使用 pgeocode python 库的数据库引擎运行的 SQL 语句。

You do have some options though.不过,您确实有一些选择。 If you are always querying all results, you can do this, which loads all of the rows and then sorts them using Python:如果您总是查询所有结果,您可以这样做,它会加载所有行,然后使用 Python 对它们进行排序:

neighbor = list(sorted(
  database.query(DataBase).all(), 
  key=lambda d: getdistance(input_zipcode, d.zipcode)
)

My guess is this would be performant enough for your needs after maybe 10,000 records or so.我的猜测是,在大约 10,000 条记录之后,这将足以满足您的需求。

Otherwise, you will need to find a way for your database engine to calculate the distance-based-on-zip-code (stored procedures, table lookups, GIS extensions, etc).否则,您将需要为您的数据库引擎找到一种方法来计算基于邮政编码的距离(存储过程、表格查找、GIS 扩展等)。

If you do happen to be using SQLite, then you COULD actually register a custom function for SQLite to call, allowing an order_by clause to work (but the performance should not be drastically different than the above solution).如果您确实使用 SQLite,那么您实际上可以注册一个自定义函数供 SQLite 调用,从而允许 order_by 子句起作用(但性能不应与上述解决方案有很大不同)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM