我认为我和here on SO.使用python 3.5,flask-sqlalchemy和sqlite有同样的问题。我正在尝试建立一个(用户)到多个(后)关系。
class User(db_blog.Model):
id = db_blog.Column(db_blog.Integer, primary_key=True)
nickname = db_blog.Column(db_blog.String(64), index=True, unique=True)
email = db_blog.Column(db_blog.String(120), unique=True)
posts = db_blog.relationship('Post', backref='author', lazy='dynamic')
def __repr__(self):
return '<User: {0}>'.format(self.nickname)
class Post(db_blog.Model):
id = db_blog.Column(db_blog.Integer, primary_key=True)
body = db_blog.Column(db_blog.String(2500))
title = db_blog.Column(db_blog.String(140))
user_id = db_blog.Column(db_blog.Integer, db_blog.ForeignKey('user.id'))
def __init__(self, body, title, **kwargs):
self.body = body
self.title = title
def __repr__(self):
return '<Title: {0}\nPost: {1}\nAuthor: {2}>'.format(self.title, self.body, self.author)
作者是无。
>>> u = User(nickname="John Doe", email="jdoe@email.com")
>>> u
<User: John Doe>
>>> db_blog.session.add(u)
>>> db_blog.session.commit()
>>> u = User.query.get(1)
>>> u
<User: John Doe>
>>> p = Post(body="Body of post", title="Title of Post", author=u)
>>> p
<Title: Title of Post
Post: Body of post
Author: None> #Here I expect- "Author: John Doe>"
我在帖子的会话添加/提交后得到相同的结果,因此无法找到帖子作者。
答案 0 :(得分:1)
如果您将新创建的post
添加到用户的posts
属性,它将起作用:
>>> u = User(nickname="John Doe", email="jdoe@email.com")
>>> u
<User: John Doe>
>>> db_blog.session.add(u)
>>> p = Post(body="Body of post", title="Title of Post")
>>> p
<Title: Title of Post
Post: Body of post
Author: None>
>>> db_blog.session.add(p)
>>> db_blog.session.commit()
>>> u.posts.append(p)
>>> p
<Title: Title of Post
Post: Body of post
Author: <User: John Doe>>
>>> p.author
<User: John Doe>
您的代码无法正常工作的原因,是因为您为__init__
类定义了Post
构造函数,而这并不考虑author
字段所有,所以Python不知道如何处理author
参数。
答案 1 :(得分:0)
您已将自己的__init__
添加到Post
。虽然它接受关键字参数,但它对它们没有任何作用。您可以更新它以使用它们
def __init__(self, body, title, **kwargs):
self.body = body
self.title = title
for k, v in kwargs:
setattr(self, k, v)
或者,理想情况下,您可以删除该方法并让SQLAlchemy为您处理它。