如何在SQLAlchemy中查询这些外键关系?

时间:2016-11-22 05:42:55

标签: sql sqlalchemy foreign-keys flask-sqlalchemy

我有以下3个SQL Alchemy模型

class MyModelA(db.Model):
    a_id   = db.Column(db.Integer, nullable=False, primary_key=True)
    my_field1 = db.Column(db.String(1024), unique=True)

class MyModelB(db.Model):
    b_id   = db.Column(db.Integer, nullable=False, primary_key=True)
    my_field2 = db.Column(db.String(1024), nullable=True)

    def my_method(self, arg_my_field1):
        pass # what goes here??

class MyModelC(db.Model, Timestamp):
    c_id = db.Column(db.Integer, nullable=False, primary_key=True)
    a_id = db.Column(db.Integer, db.ForeignKey(MyModelA.a_id), default=lambda: MyModelA.query.filter(MyModelA.my_field1 == 'XYZ').one().a_id)
    a = db.relationship('MyModelA', backref=db.backref('my_model_c'))
    b_id = db.Column(db.Integer, db.ForeignKey(MyModelB.b_id), nullable=False)
    b = db.relationship('MyModelB', backref=db.backref('my_model_c'))
    my_field3 = db.Column(db.String(1024), unique=True)
    __table_args__ = (db.UniqueConstraint('a_id', 'b_id', name='unique_constraint_aid_bid'),)

在方法my_method中,我想返回my_field3实例的MyModelC字段(指向self并指向MyModelA my_field1作为不区分大小写的匹配arg_my_field1。应该有最多一个这样的实例。如果没有MyModelC的此类实例,则返回None

我应该在my_method中编写哪些SQLAlchemy查询来实现该结果?

1 个答案:

答案 0 :(得分:0)

以下是答案

def my_method(self, arg_my_field1):
    return self.my_model_c.join(MyModelA).filter(MyModelA.my_field1.ilike(arg_my_field1)).one().my_field3

需要将lazy='dynamic'添加到MyModelC中的两个关系中,如下所示:

class MyModelC(db.Model, Timestamp):
    c_id = db.Column(db.Integer, nullable=False, primary_key=True)
    a_id = db.Column(db.Integer, db.ForeignKey(MyModelA.a_id), default=lambda: MyModelA.query.filter(MyModelA.my_field1 == 'XYZ').one().a_id)
    a = db.relationship('MyModelA', backref=db.backref('my_model_c', lazy='dynamic'))
    b_id = db.Column(db.Integer, db.ForeignKey(MyModelB.b_id), nullable=False)    # MODIFIED
    b = db.relationship('MyModelB', backref=db.backref('my_model_c', lazy='dynamic'))    # MODIFIED
    my_field3 = db.Column(db.String(1024), unique=True)
    __table_args__ = (db.UniqueConstraint('a_id', 'b_id', name='unique_constraint_aid_bid'))