一对多Flask SQLAlchemy

一对多Flask SQLAlchemy,第1张

一对多Flask SQLAlchemy

好吧,我想您想念电影中的角色关系了+插入内容并非完全正确。

还有一些细节,您必须要小心。为什么电影的id是movieS_id,字符的id是character_id?

另外,如果未指定,则列名与变量名相同。

例如,您可以这样做:

character_description = db.Column(db.Text())
无论如何,在不更改此详细信息的情况下,您可以尝试以下 *** 作:
class Movie(db.Model):    __tablename__ = "movies"    id = db.Column('movies_id', db.Integer, primary_key=True)    movie_type = db.Column('movie_type', db.Text())    characters = db.relationship("Character", backref="movie", lazy='dynamic')    def __init__(self, movie_type):        self.movie_type = movie_type    def __repr__(self):        return '<Movie %r>' % self.idclass Character(db.Model):    __tablename__ = "characters"    id = db.Column('character_id', db.Integer, primary_key=True)     character_description = db.Column('character_description', db.Text())    movie_id = db.Column(db.Integer, db.ForeignKey('movies.movies_id'))    movie = db.relationship('Movie')    def __init__(self, character_description, movie):        self.character_description = character_description        self.movie = movie    def __repr__(self):        return '<Character %r>' % self.id
插入
c = Character(character_description='c')c2 = Character(character_description='c2')m = Movie(movie_type ='action')# link characters to moviem.characters.append(c)m.characters.append(c2)# orm.characters.extend([c,c2])db.session.add(m)# add charactersdb.session.add(c)db.session.add(c2)# ordb.session.add_all([c,c2])# commitdb.session.commit()


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5642902.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存