Al Nikolaj
Al Nikolaj

Reputation: 315

How to set Integer field to optional in Flask-Marshmallow?

I have the following Model and its corresponding Schema. The field sold_price is causing an issue if I try to leave the field empty. I raises the error "Not a valid integer", which is technically true, but I need to make the field optional / allow null.

# Models.py
class Product(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    sold_price = db.Column(db.Integer)

# Marshmallow
class ProductSchema(SQLAlchemyAutoSchema):
    class Meta:
        model = Product
    id = auto_field(dump_only=True)
    sold_price = auto_field()

I managed to find a suboptimal solution, but I have the feeling there must a better way. The suboptimal solution compromises a custom field:

class OptionalInteger(fields.Field):

    def _serialize(self, value, attr, obj, **kwargs):
        if value is None:
            return ''
        return value

    def _deserialize(self, value, attr, data, **kwargs):
        if value:
            try:
                return int(value)
            except ValueError as error:
                raise ValidationError("Must a integer") from error
        return value

Any other ideas how to make the sold_price (int) field optional?

Upvotes: 1

Views: 2604

Answers (1)

Jérôme
Jérôme

Reputation: 14674

My guess is the field in your input data is not missing but null. This is typical of a HTML form where the field is left blank.

By default, the DB field is not nullable, so the generated field

  • is not required (required = False)
  • allows None (allow_none = True)

This happens here: https://github.com/marshmallow-code/marshmallow-sqlalchemy/blob/6e43a8357a012fb08ee1ec32e67c07679a97b917/src/marshmallow_sqlalchemy/convert.py#L264-L266

You can check that by printing

print(ProductSchema().fields['sold_price'].required)
print(ProductSchema().fields['sold_price'].allow_none)

I can't explain your problem without a code sample showing the validation error.

Upvotes: 1

Related Questions