SQLAlchemy与烧瓶关系

时间:2018-11-07 23:56:25

标签: python flask flask-sqlalchemy

更新:由于我发表的评论之一,我确实添加了关联表:

association = db.Table('association',
    db.Column('user_id', db.Integer, db.ForeignKey('user.id'), primary_key=True),
    db.Column('restaraunt_id', db.Integer, db.ForeignKey('restaraunt.id'), primary_key=True)
)

效果很好,在外壳上,我能够:

u=User(username='bob', email='bob@villa.com')
db.session.add(u)
db.session.commit()
r=Restaraunt(name='Five Guys', costRating=4)
db.session.add(r)
db.session.commit()
rp=RestarauntPreferences(user=u, restaraunt=r, rating=0)
db.session.add(rp)
db.session.commit()

然后:

rp.restaraunt.name
['Five Guys']

真棒。但是... db.session.add(rp)将重复的条目添加到RestarauntPreferences表中吗?我如何声明关联?我还没有得到有关SQLAlchemy和flask的其他信息? (并且使用数据库浏览器查看sqlite数据库,在运行shell命令后,关联表中没有任何信息,不确定这是否正确...)

原点发布:(以下模型)

我正在尝试构建使用SQLAlchemy的小烧瓶应用程序。我尝试使用的模型以及与之建立工作关系的模型是多对多的。下面介绍了它们以及我的用法。

(基本上,一个用户可以给多家餐馆打分)

#how do I use these??

rprefs=RestarauntPreferences.query.filter_by(user=current_user) 
rprefs.restaraunt.name   #doesn't work, doesn't know what restaraunt is

#models below

class User(UserMixin, db.Model):
    __tablename__ = 'user'

    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(64), index=True, unique=True)
    email = db.Column(db.String(120), index=True, unique=True)
    password_hash = db.Column(db.String(128))
    recipient_idf= db.Column(db.String(256))
    first_name = db.Column(db.String(128))
    last_name = db.Column(db.String(128))
    most_recent_lunch_date = db.Column(db.DateTime)
    lunch_Rating = db.Column(db.Integer)
    phone_number = db.Column(db.String(128))

    def set_password(self, password):
        self.password_hash = generate_password_hash(password)

    def check_password(self, password):
        return check_password_hash(self.password_hash, password)

    def __repr__(self):
        return '<User {} {}>'.format(self.username, self.recipient_idf)


class Restaraunt(db.Model):
    __tablename__ = 'restaraunt'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(128))
    costRating = db.Column(db.Integer)

    def __repr__(self):
        return '<Restaraunt {} {}>'.format(self.name, self.costRating)


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

    restaraunt_id = db.Column(db.Integer, db.ForeignKey('restaraunt.id'))
    restaraunt = relationship("Restaraunt", foreign_keys=[restaraunt_id])

    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    user = relationship("User", foreign_keys=[user_id])

    rating = db.Column(db.Integer)


    def __repr__(self):
        return '<RestarauntPref {} {} {}>'.format(self.restaraunt_id, self.user_id, self.rating)

1 个答案:

答案 0 :(得分:1)

Flask-SqlalchemySqlalchemy的文档均声明,要使多对多关系正常工作,需要一个关联表。尝试像在示例中那样创建它,并将其作为secondary参数添加到声明中。