Flask SQLalchemy多对多关系,出于某种原因需要secondaryjoin和primaryjoin

时间:2014-11-21 21:45:24

标签: flask sqlalchemy flask-sqlalchemy

在SQLAlchemy docs中,http://docs.sqlalchemy.org/en/rel_0_9/orm/relationships.html一切都应该可以正常工作但我收到一个名为

的错误

原始异常是:无法确定关系User.rank_r上的父/子表之间的连接条件。指定'主要连接'表达。如果' secondary'存在,' secondaryjoin'也需要。

class User(db.Model, UserMixin):

    __tablename__ = 'users'
    rank_r = db.relationship('Rank', 
                               secondary=ranks, 
                               backref=db.backref('users', lazy='dynamic'))


class Rank(db.Model):
    __tablename__ = 'rank'
    id = Column(db.Integer, primary_key=True)
    name = Column(db.String(STRING_LEN), nullable=False, unique=True)


ranks = db.Table('ranks',    
    db.Column('rank_id', db.Integer, db.ForeignKey('rank.id')),
    db.Column('user_id', db.Integer, db.ForeignKey('users.id'))
)

基本上我正在尝试这样做:

SELECT u.id, u.name, r.name users u INNER JOIN ranks r ON r.id=rr.rank_id INNER JOIN rank rr ON rr.user_id==u.id 

这将返回如下内容:

1 Bob Major
2 Joey Captain
3 Adam Brigadier General

此关系代码似乎也失败了:

rank_r = db.relationship('Rank', 
                           primaryjoin="(rank.c.id==ranks.c.rank_id)",
                           secondary="ranks", 
                           secondaryjoin="(id==ranks.c.user_id)",
                           backref=db.backref('users', lazy='dynamic'))

有错误:

StatementError:在mapper Mapper | User | users ...上没有配置列rank.id(原因:UnmappedColumnError:没有列rank.id在mapper Mapper | User | users ...上配置)' SELECT rank.id AS rank_id,rank.name AS rank_name \ nFROM排名,排名,用户\ nWHERE? = shares.rank_id AND users.id = ranking.user_id' [immutabledict({})]

当我尝试呼叫" User.rank_r"时显示的内容在模板中。

1 个答案:

答案 0 :(得分:1)

你的代码似乎没问题,我删除了一些东西(只是为了减少我的导入),它似乎做了你之后的事情:

from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy


app = Flask(__name__)
app.secret_key = 'MOO.'
app.config["SQLALCHEMY_DATABASE_URI"] = 'sqlite://'  # In memory.
db = SQLAlchemy(app)


ranks = db.Table('ranks',
    db.Column('rank_id', db.Integer, db.ForeignKey('rank.id')),
    db.Column('user_id', db.Integer, db.ForeignKey('users.id'))
)

class User(db.Model):
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String())
    ranks = db.relationship('Rank',secondary=ranks,
                               backref=db.backref('users', lazy='dynamic'))

    def __init__(self, name):
        self.name = name

    def __repr__(self):
        return self.name


class Rank(db.Model):
    __tablename__ = 'rank'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(), nullable=False, unique=True)

    def __repr__(self):
        return self.name

@app.route('/')
def hello_world():
    return 'Hello World!'


if __name__ == '__main__':
    with app.app_context():
        db.create_all()
        bob = User('Bob')
        joey = User('Joey')
        adam = User('Adam')

        major = Rank(name='Major')
        captain = Rank(name='Captain')
        general = Rank(name='General')

        db.session.add_all([bob, joey, adam, major, captain, general])

        bob.ranks.append(major)
        joey.ranks.append(captain)
        adam.ranks.append(general)
        adam.ranks.append(captain)

        db.session.commit()

        users = User.query.all()
        for user in users:
            for rank in user.ranks:
                print '{} {}'.format(user, rank)

                # Bob Major
                # Joey Captain
                # Adam Captain
                # Adam General