SQLAlchemy:@属性映射? [英] SQLAlchemy: @property mapping?

查看:71
本文介绍了SQLAlchemy:@属性映射?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下型号:

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

现在,我想使用过滤器来运行查询,该过滤器取决于已定义的属性.我得到空结果(当然,正确的数据在DB中).它不起作用,因为可能必须映射此属性.问题是如何做到这一点? (一个限制:不允许FK.)

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()

推荐答案

您可以使用常规的关联代理:

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')

由于架构中没有外键,因此您需要自己告诉SQLAlchemy relationship的连接条件.这就是remote()foreign()注释的作用.

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.

在此位置上,您可以使用association_proxy跨"关系在Data上创建一个属性,该属性将按您想要的方式工作.

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.

这篇关于SQLAlchemy:@属性映射?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆