2015-08-14 49 views
0

这里是我的岗位模型:烧瓶sqlachemy不能追加并使用backref

class Post(UserMixin,db.Model): 
    __tablename__ = "posts" 

    id = db.Column(db.Integer,primary_key = True) 
    posts = db.Column(db.String(500)) 
    post_author = db.Column(db.Integer,db.ForeignKey("users.id")) 

这里是我的用户模型:

class User(UserMixin,db.Model): 
     __tablename__ = "users" 
     id = db.Column(db.Integer,primary_key = True) 
     username = db.Column(db.String(60),unique = True, index = True) 
     first_name = db.Column(db.String(60),unique = True, index = True) 
     last_name = db.Column(db.String(60), index = True) 
     password = db.Column(db.String(100)) 



     user_post = db.relationship("Post",secondary = post , primaryjoin = (post.c.user_id == id), secondaryjoin = (post.c.post_id == Post.id), 
     backref = db.backref("authored_post",lazy = "dynamic"),lazy = "dynamic") 

现在我有一个名为authored_post

后模型backref

这是我试过

db.session.add(Post(posts = posted, post_author = current_user.id, authored_post = current_user)) 

因为基本上我想要做的是查询所有帖子,并找出谁通过backref创作每篇文章,所以我可以得到他们的last_name属性,但做authored_post = current_user将返回一个错误,说一个错误,说User object is not iterable

追加到它不会工作Post.authored_post.append(current(user)) 它也会引发错误。那么我们如何解决这个问题呢?

回答

0

以供其他遇到此类问题的人参考。

我解决了它这样做

class Post(UserMixin,db.Model): 
    __tablename__ = "posts" 

    id = db.Column(db.Integer,primary_key = True) 
    posts = db.Column(db.String(500)) 
    post_author = db.Column(db.Integer,db.ForeignKey("users.id")) 
    author = db.relationship("Users") 

我的解决方法是简单地增加相互之间的关系,所以当你做

db.session.add(Post(posts = posted, post_author = current_user.id, author = current_user)) 

如果查询所有类似的帖子对象,并得到各indivual对象:

post = [i for i in Post.query.all()] 

您现在可以访问Users m上的所有属性奥德尔!

只是做:

for i in post: 
print(i.author.first_name,i.author.last_name) 

进出口新的SQLAlchemy的和公平的新的Python等等。我希望帮助一些新手