从连接表中添加列

时间:2015-01-16 18:45:22

标签: python flask sqlalchemy flask-sqlalchemy

我正在使用Python 2.7 + flask-sqlalchemy。我定义了以下模型/表:

class Detail(db.Model):
    __tablename__ = 'details'
    id = db.Column(db.Integer, primary_key=True)
    ....

class Usage(db.Model):
    __tablename__ = 'details'
    id = db.Column(db.Integer, primary_key=True)
    details = db.relationship('Detail', secondary=details_usages, backref=db.backref('usages', lazy='dynamic'))
    ....

details_usages = db.Table('details_usages',
    db.Column('detail_id', db.Integer, db.ForeignKey('details.id')),
    db.Column('usage_id', db.Integer, db.ForeignKey('usages.id')),
    db.Column('is_required', db.Integer)
)

我有以下查询:

models.Detail.query.join(details_usages).add_columns('details_usages.is_required').all()

我收到以下错误:

NoSuchColumnError:“找不到列'details_usages.is_required'的行中的列<”

我做错了什么?

1 个答案:

答案 0 :(得分:2)

我找到了解决方案。正确的查询方式应该是:

models.Detail.query.join(details_usages).add_columns(details_usages.c.is_required).all()