0

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
Vishal Verma
  • 43
  • 1
  • 6

1 Answers1

1

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.

Nagaraj Tantri
  • 5,172
  • 12
  • 54
  • 78
NMO
  • 748
  • 8
  • 16