我有两个模型,我想将它们关联起来(多对多),但我不想为此使用辅助表,因为位置(geom 属性)会不断变化。我正在使用 ST_Intersects,这是来自 postgis 的函数并返回一个布尔值,当几何与其他几何相交时为真。
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.sql.functions import func
from flask import Flask
from geoalchemy2.types import Geometry
db = SQLAlchemy()
def create_app():
app = Flask(...)
...
db.init_app(app)
...
return app
class City(db.Model):
__tablename__ = "city"
id = db.Column(db.Integer, primary_key=True)
geom = db.Column(Geometry("POLYGON",4326))
...
class Location(db.Model):
__tablename__ = "location"
id = db.Column(db.Integer, primary_key=True)
geom = db.Column(Geometry("POLYGON",4326))
...
cities = db.relationship(City, primaryjoin=func.ST_Instesects(geom,City.geom), remote_side=id, foreign_keys=City.id, viewonly=True, uselist=True, lazy='joined')
使用此配置抛出异常
sqlalchemy.exc.ArgumentError: Relationship Location.cities could not determine any unambiguous local/remote column pairs based on join condition and remote_side arguments. Consider using the remote() annotation to accurately mark those elements of the join condition that are on the remote side of the relationship.
但是如果我在primaryjoin中添加remote()和foreign(),sqlalchemy会抛出同样的异常
使用纯 SQL,我可以:
SELECT city.* FROM location loc JOIN city ON ST_Intersects(city.geom,loc.geom)