【问题标题】:How to add a custom field in Flask-Marshmallow which is not a part of my SQLAlchemy Model如何在不属于我的 SQLAlchemy 模型的 Flask-Marshmallow 中添加自定义字段
【发布时间】:2020-10-25 06:44:47
【问题描述】:

假设我的模型类如下。

class BankAccount(db.Model):
    a = db.Column(db.Integer, primary_key=True)
    b = db.Column(db.String(80))

我的架构如下所示。

class CreateAccountSchema(ma.SQLAlchemyAutoSchema):
    class Meta:
        model = BankAccount
        load_instance = True
        ordered = True

但在这里我想定义一个字段 c 不存在于我的模型类中,因为它应该只用于转储(ing)值而不是存储在数据库中。 有点像...

class CreateAccountSchema(ma.SQLAlchemyAutoSchema):
    class Meta:
        model = BankAccount
        dump_only = ('c',)
        load_instance = True
        ordered = True
        c = #somedefination

【问题讨论】:

    标签: flask-sqlalchemy flask-restful marshmallow flask-marshmallow marshmallow-sqlalchemy


    【解决方案1】:

    你可以这样做:

    class CreateAccountSchema(ma.SQLAlchemyAutoSchema):
        class Meta:
            model = BankAccount
            load_instance = True
            ordered = True
            c = fields.Method("get_data")
    
        def get_data(self, obj):
            if hasattr(obj, "data"):
                return obj.data
            return None
    

    这将转储附加字段。 你可以这样使用它:

    bank_account = db.session.query(BankAccount).first()
    bank_account.data = "whatever"
    schema = CreateAccountSchema()
    schema.dump(bank_account)
    

    更多信息here.

    【讨论】:

      猜你喜欢
      • 2013-07-30
      • 1970-01-01
      • 2016-12-22
      • 2014-12-01
      • 2019-01-28
      • 1970-01-01
      • 2015-09-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多