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

时间:2017-05-19 18:51:58

标签: python flask sqlalchemy geoalchemy2

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

0 个答案:

没有答案
相关问题