sqlalchamy更新一对多关系

时间:2017-09-14 14:44:25

标签: python sqlalchemy flask-sqlalchemy

我正在编写简单的falsk应用程序并使用flask_marshmallow。

我有以下代码

class AuthorSchema(ma.ModelSchema):
    class Meta:
        model = Author

class BookSchema(ma.ModelSchema):
    class Meta:
        model = Book

db.create_all()

#  Scenario 1: insert new author and new book
data = {'books': [{"title":"xyz"}], 'name': 'Chuck Paluhniuk'}
aschema = AuthorSchema().load(data).data
aschema.firstbook = aschema.books[0].title
db.session.add(aschema)
db.session.commit()

# Scenario 2:  update existing author and insert new book
updated =  {'books': [{"title":"cat"}], 'name': 'Chuck Paluhniuk'}
aschema = AuthorSchema().load(updated).data
author = db.session.query(Author).filter_by(name=aschema.name).first()
author.firstbook =  aschema.books[0].title
author.books.append(aschema.books[0])
db.session.commit()

我正在使用sqllite。我有上面代码中提到的两个场景。当我运行上面的代码时,

预期的结果是,

1 record in author table (first book = cat, after update) 
2 records in book table. 

但是我在作者表中看到了2条记录。一个空头的第一本书。上面的代码出了什么问题?enter image description here

0 个答案:

没有答案