Search code examples
flask-sqlalchemyflask-restfulmarshmallowflask-marshmallowmarshmallow-sqlalchemy

How to add a custom field in Flask-Marshmallow which is not a part of my SQLAlchemy Model


Suppose I have my Model class as below.

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

And my Schema looks like the below.

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

But here I want to define a field c which doesnt exists in my Model class as it should only be used for dump(ing) values and not storing in the database. Something like...

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

Solution

  • You could do something like this:

    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
    

    That would dump the additional field. You could use it like this:

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

    More infos here.