Search code examples
flasksqlalchemymarshmallow

Custom field names in SQLAlchemy Meta Class Marshmellow


I'm trying to use .dump for a query result using marshmallow from my sqlAlchemy query, but I would like to have the field's name custom (Not the same as the DB table column name) to send to the front-end.

So if my table schema is:

class SomeRandomName(db.Model):
    __tablename__ = 'some_random_name'
    id = db.Column(db.Integer, primary_key=True)
    time = db.Column(db.DateTime, default=datetime.utcnow)
    title = db.Column(db.String(30), unique=False, nullable=True)
    some_column_name = db.Column(db.String(30), unique=False, nullable=True)

And my Marshmallow Schema is:

class SomeRandomNameSchema(ma.Schema):
    class Meta:
        fields = ["time", "title", "some_column_name"]

The response will be:

[
    {"time": "2020-07-17 07:18:44",
    "title": "Some Title",
    "some_column_name": false}
]

but what I actually want is that my column name stays the same in DB but change the Key in the JSON response without manipulating the JSON after the .dump.

For Example:

[
    {"time": "2020-07-17 07:18:44",
    "title": "Some Title",
    "CulmnNameChanged": false}
]

I also tried suggested answers in here but I end up with an empty JSON response.

the only way I could get the data was by putting fields = ["time", "title", ...] in my Class Meta


Solution

  • So in the process of creating a reproducible example as requested in the comments, I ended up finding the answer which was by adding the many=True to the Marshmallow schema class since I was using .all() in my query and also using the suggested answer for my schema structure.

    I will leave this here just as an example if anyone had the issue:

    from app import db, ma
    from marshmallow import fields
    
    
    class Table(db.Model):
        __tablename__ = 'table'
        id = db.Column(db.Integer, primary_key=True)
        title = db.Column(db.String(30), unique=False, nullable=True)
    
    
    class TableSchema(ma.Schema):
        class Meta:
            strict = True
        newTitleName = fields.String(attribute="title")
    
    
    def my_function():
        _query = db.session.query(Table).all()
        ser = TableSchema(many=True)
        result = ser.dump(_query)
        print(result)
    
    
    my_function()