SQLAlchemy: @property mapping?

非 Y 不嫁゛ 提交于 2019-12-11 02:26:10

问题


I have following models:

class Details(db.Model):

    details_id = db.Column(db.Integer, primary_key=True)
    details_main = db.Column(db.String(50))
    details_desc = db.Column(db.String(50))

class Data(db.Model):

    data_id = db.Column(db.Integer, primary_key=True)
    data_date = db.Column(db.Date)
    details_main = db.Column(db.String(50))

    @property
    def details_desc(self):

        result = object_session(self).\
            scalar(
                select([Details.details_desc]).
                    where(Details.details_main == self.details_main)
            )

        return result

Now, I would like to run query using filter which depends on defined property. I get empty results (of course proper data is in DB). It doesn't work because, probably, I have to map this property. The question is how to do this? (One limitation: FK are not allowed).

Data.query\
    .filter(Data.details_desc == unicode('test'))\
    .all()

回答1:


You can implement this with a regular relationship and an association proxy:

class Data(db.Model):
    data_id = db.Column(db.Integer, primary_key=True)
    data_date = db.Column(db.Date)
    details_main = db.Column(db.String(50))

    details = relationship(
        Details,
        primaryjoin=remote(Details.details_main) == foreign(details_main))
    details_desc = association_proxy('details', 'details_desc')

Since there are no foreign keys in the schema, you need to tell SQLAlchemy yourself what the join condition for the relationship should be. This is what the remote() and foreign() annotations do.

With that in place, you can use an association_proxy "across" the relationship to create a property on Data which will work the way you want.



来源:https://stackoverflow.com/questions/35653889/sqlalchemy-property-mapping

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!