Search code examples
pythonmarshmallowmarshmallow-sqlalchemy

How to override dump() to avoid returning one of the columns


Using flask SQLalchemy and marshmallow, I'm trying to get all users in my DB with this instruction:

users = Users.query.all()
result = users_schema.dump(users)

But it always returns a password column, how could I avoid it?

This is my model:

class Users(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(400))
    password = db.Column(db.String(200))
    role_id = db.Column(db.Integer, db.ForeignKey('roles.id'))
    token = db.Column(db.Text)
    username = db.Column(db.String(200), unique=True)

   def __init__(self, name, password, role_id, token, username):
        self.name = name
        self.password = password
        self.role_id = role_id
        self.token = token
        self.username = username

I want to get all users without the password column.


Solution

  • You can exclude the entire field in the schema metaclass.
    List all fields to be excluded from serialization within a sequence and assign this to the exclude keyword. So these fields are ignored.

    class UsersSchema(ma.SQLAlchemyAutoSchema):
        class Meta: 
            model = Users
            exclude = ('password',)
        # ...
    

    Alternatively, you can define the field as a write-only field with the load_only attribute.

    class UsersSchema(ma.SQLAlchemyAutoSchema):
        class Meta: 
            model = Users
            load_instance = True
        password = ma.String(load_only=True)
        # ...