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.
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.
SqlAlchemy-Marshmallow provides few examples on how to use the ModelSchemas, one about Overriding generated fields corresponds to your needs:
Any field generated by a ModelSchema can be overridden.
You could for example simply manually specify the field and use the attribute
parameter of the field
object:
from marshmallow import fields
class someSchema(ma.ModelSchema):
x = fields.Integer(attribute='y') # Or vice-versa
class Meta:
model = someModel
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With