Search code examples
pythonsqlalchemymarshmallow

How to change the name of fields using SqlAlchemy-Marshmallow?


i'm using SQLAlchemy - Marshmallow for schema creation, it roughly looks like this:

class someModel(db.Model):
  y_x = db.Column(db.BigInteger, primary_key = True)

class someSchema(ma.ModelSchema):
  class Meta:
    model = someModel

The problem I'm having is the JSON object that I want to use has the property x, {"x": 1}, not y_x. Is there a way for the schema to recognize this? I'm aware in Marshmallow you can do y = fields.Integer(data_key="x") But i'm not sure if this works with Marshmallow flask, and if you can add this after model = someModel or not.


Solution

  • I was having this exact problem and attempting to fix it by adding a manual field override to my schema definition. This was creating a collision between the field being generated automatically from the model and the field I manually defined. It turns out if you override fields manually, they need to be excluded from inference by explicitly marking them as excluded from the Meta class. Something like this ended up working for me:

    class FooSchema(ma.ModelSchema):
        id = fields.Integer(attribute="foo_id")
        class Meta:
           model = Foo
           exclude = ["foo_id"]
    

    Hope this saves somebody some time digging through Marshmallow-SQLAlchemy source.