SqlAlchemy 关系和 Marshmallow

SqlAlchemy Relationship and Marshmallow

我正在尝试 return JSON 甚至 returned 一对多 sqlalchemy 查询的完整字符串。我现在正在使用 Marshmallow 来尝试这样做,但它保持 returning 不完整的数据

我有两个模型定义为:

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': {}

有谁知道我如何正确地做到这一点

是一对多关系,必须在UserSchema上注明,这样

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

阅读更多关于 documentation