Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 652
Javier Moran Lemus Avatar asked Mar 19 '19 18:03

Javier Moran Lemus


2 Answers

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.

like image 177
Exley McCormick Avatar answered Oct 29 '22 11:10

Exley McCormick


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
like image 26
CloC Avatar answered Oct 29 '22 12:10

CloC