如何在SQLAlchemy中执行此复杂的外键查询?

时间:2016-11-22 01:44:30

标签: mysql database 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并指向MyModelAmy_field1==arg_my_field1)。应该有最多一个这样的实例。如果没有MyModelC的此类实例,则返回None。我该怎么写这个方法?

1 个答案:

答案 0 :(得分:0)

以下是答案

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')) 中的两个关系中,如下所示:

Dateop               Shift  Crew
2015-12-23 00:00:00  D      B Crew
2015-12-23 00:00:00  N      A Crew
2015-12-24 00:00:00  D      B Crew
2015-12-24 00:00:00  N      A Crew
2015-12-25 00:00:00  D      C Crew
2015-12-25 00:00:00  N      B Crew
2015-12-26 00:00:00  D      C Crew
2015-12-26 00:00:00  N      B Crew
2015-12-27 00:00:00  D      C Crew
2015-12-27 00:00:00  N      B Crew
2015-12-28 00:00:00  D      C Crew
2015-12-28 00:00:00  N      B Crew
2015-12-29 00:00:00  D      C Crew
2015-12-29 00:00:00  N      B Crew
2015-12-30 00:00:00  D      A Crew
2015-12-30 00:00:00  N      C Crew
2015-12-31 00:00:00  D      A Crew
2015-12-31 00:00:00  N      C Crew
2016-01-01 00:00:00  D      A Crew
2016-01-01 00:00:00  N      C Crew
2016-01-02 00:00:00  D      A Crew
2016-01-02 00:00:00  N      C Crew