1

I want to create a relationship between two models that have Geometry columns. For example:

from geoalchemy2.types import Geometry
from flask.ext.sqlalchemy import SQLAlchemy
from myapp import app

db = SQLAlchemy(app)

class Property(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    street_address = db.Column(db.Text)
    geom = db.Column(Geometry(geometry_type='POINT'))

    service_areas = db.relationship(
        'ServiceArea',
        primaryjoin='ServiceArea.geom.ST_Contains(Geocode.geom)',
        lazy='joined',
        uselist=True,
        viewonly=True,
    )

class ServiceArea (db.Model):
    name = db.Column(db.Text)
    value = db.Column(db.Text)
    geom = db.Column(Geometry(geometry_type='MULTIPOLYGON'))

In this example, a Property may be associated with many ServiceAreas, and a ServiceArea may be associated with many properties. However, there's not a secondary table for me to use for the relationship -- it is all determined by the ST_Contains function.

Whenever I run this code, I get an sqlalchemy.exc.ArgumentError exception telling me to "Ensure that referencing columns are associated with a ForeignKey or ForeignKeyConstraint, or are annotated in the join condition with the foreign() annotation."

When I add foreign around the ServiceArea.geom (even though it's not a foreign key), I get an error suggesting that I "Consider using the remote() annotation to accurately mark those elements of the join condition that are on the remote side of the relationship."

I've tried using foreign and remote separately as well as together (e.g., foreign(remote(ServiceArea.geom)) and remote(foreign(ServiceArea.geom))) but always get back one of the above errors. What am I doing wrong?

mjumbewu
  • 1,104
  • 5
  • 14
  • 28

0 Answers0