9

我正在尝试返回 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': {}

有谁知道我怎样才能正确地做到这一点

4

1 回答 1

18

这是一对多的关系,你必须在 上注明UserSchema,就像那样

class UserSchema(Schema):
    id = fields.Int(dump_only=True)
    username = fields.Str()
    password = fields.Str()
    weekday = fields.Nested(WeekdaySchema, many=True)

阅读有关文档的更多信息

于 2016-06-14T02:57:57.217 回答