我正在尝试将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': {}
没有人知道我怎么能正确地做到这一点
答案 0 :(得分:6)
这是一对多的关系,您必须在UserSchema
上注明,就像那样
class UserSchema(Schema):
id = fields.Int(dump_only=True)
username = fields.Str()
password = fields.Str()
weekday = fields.Nested(WeekdaySchema, many=True)
详情请阅读documentation