首页 文章

SqlAlchemy关系和棉花糖

提问于
浏览
1

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

没有人知道我怎么能正确地做到这一点

1 回答

  • 2

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

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

    阅读更多documentation

相关问题