繁体   English   中英

SQLALchemy - 没有映射外键的关系,使用带有func的自定义主连接

[英]SQLALchemy - relationship without mapped foreign keys, using custom primaryjoin with func

我有两个模型,我想关联它们(多对多),但我不想使用辅助表,因为位置(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)

暂无
暂无

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

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