One-to-many Flask | SQLAlchemy

↘锁芯ラ 提交于 2019-11-30 19:07:11

Well, I think you miss the characters relations in the movie + the insert was not totaly right.

There is also little details that you have to be carefull. Why id of movie is movieS_id and id of character is character_id ?

Also, the name of the column is the same as the name of the variable if not specified.

For example you can do that:

character_description = db.Column(db.Text())

Anyway, without changing this details, you can try this:

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.id

class 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

Inserting

c = Character(character_description='c')
c2 = Character(character_description='c2')
m = Movie(movie_type ='action')

# link characters to movie
m.characters.append(c)
m.characters.append(c2)
# or
m.characters.extend([c,c2])

db.session.add(m)
# add characters
db.session.add(c)
db.session.add(c2)
# or
db.session.add_all([c,c2])
# commit
db.session.commit()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!