我正在尝试使用 flask-restful 制作 rest api,我使用 flask-sqlalchemy 作为 ORM。这是我的模型类。
class Post(db.Model):
__tablename__ = 'post'
postid = db.Column(db.Integer,primary_key=True)
post = db.Column(db.String(64))
userid = db.Column(db.Integer,db.ForeignKey('user.userid'))
#serialize property used for serializing this class to JSON
@property
def serialize(self):
return {
'postid': self.postid,
'post': self.post,
'author':self.author
}
和
class User(db.Model):
userid = db.Column(db.Integer,primary_key=True)
username = db.Column(db.String(30))
email = db.Column(db.String(20))
posts = db.relationship('Post',backref="author",lazy='dynamic')
#serialize property used for serializing this class to JSON
@property
def serialize(self):
return {
'username': self.username,
'email': self.email
}
并且数据库已填充。现在我正在尝试从中生成 json
class PostList(Resource):
def get(self):
posts = DL_models.Post.query.all()
posts = [post.serialize for post in posts]
return { 'posts': posts }
api.add_resource(PostList, '/twitter/api/v1.0/posts', endpoint = 'posts')
当我将 Post 中的序列化方法更改为
@property
def serialize(self):
return {
'postid': self.postid,
'post': self.post,
'author':self.postid
}
这会返回预期的 json 输出,但是当我更改为 'author':self.author
时出现错误
TypeError: <app.DL_models.User object at 0x7f263f3adc10> is not JSON serializable
我知道我也必须对那些嵌套对象调用序列化,但我不知道该怎么做。
或者请分享您在 sqlalchemy 中编码关系的经验。
最佳答案
既然您已经在使用 Flask-Restful,您是否考虑过使用它们内置的 data marshaling solution ?
但是,对于编码复杂的数据结构,我发现 Marshmallow完成任务的效果要好一千倍,甚至可以轻松地在其他序列化器中嵌套序列化器。还有一个 Flask 扩展,旨在检查端点和输出 URL。
关于python - jsonify flask-sqlalchemy flask中的多对一关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25737050/