【发布时间】:2016-10-14 08:46:39
【问题描述】:
我正在尝试返回 JSON 甚至返回的一对多 sqlalchemy 查询的完整字符串。我此时正在使用 Marshmallow 尝试这样做,但它一直返回不完整的数据
我有两个模型定义为:
class UserModel(db.Model):
__tablename__ = 'usermodel'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True)
password = db.Column(db.String(120))
weekday = db.relationship('weekDay', cascade='all,delete-orphan', single_parent=True, backref=db.backref('usermodel', lazy='joined'))
class weekDay(db.Model):
__tablename__ = 'weekday'
id = db.Column(db.Integer, primary_key=True)
#Defining the Foreign Key on the Child Table
dayname = db.Column(db.String(15))
usermodel_id = db.Column(db.Integer, db.ForeignKey('usermodel.id'))
我定义了两个模式
class WeekdaySchema(Schema):
id = fields.Int(dump_only=True)
dayname = fields.Str()
class UserSchema(Schema):
id = fields.Int(dump_only=True)
username = fields.Str()
password = fields.Str()
weekday = fields.Nested(WeekdaySchema)
最后我运行命令(我在 userName 变量中传递名称)
userlist = UserModel.query.filter_by(parentuser=userName).all()
full_schema = UserSchema(many=True)
result, errors = full_schema.dump(userlist)
print (result)
我在尝试 Jsonify 之前打印结果以查看: 我的工作日对象完全是空的
'weekday': {}
有谁知道我如何正确地做到这一点
【问题讨论】:
标签: json flask sqlalchemy marshmallow