LoginSignup
0
1

More than 3 years have passed since last update.

connexionとmarshmallow-sqlalchemyでDB定義上not nullかつdefaultありなフィールドで「Field may not be null.」が出るのを抑制した

Last updated at Posted at 2020-08-05

とりあえず動いたからよし!したけどもっと筋の良い方法もありそう。

環境

requirement.txt
# 抜粋
connexion==2.7.0
marshmallow-sqlalchemy==0.23.1
marshmallow==3.7.1
sqlalchemy==1.3.18
flask-marshmallow==0.13.0
flask-migrate==2.5.3
flask-sqlalchemy==2.4.4
flask==1.1.2

問題のColumn

model.py
hoge_date = db.Column(db.Date(), nullable=False, default=date.fromisoformat('2099-12-31'))

エラー内容

console.log
marshmallow.exceptions.ValidationError: {'hoge_date': ['Field may not be null.']}

対処

schema.py
class HogeSchema(ma.SQLAlchemyAutoSchema):
    class Meta:
        model = Hoge

    # これを追加
    @pre_load
    def remove_has_defalt_key_if_none(self, in_data: dict, **kwargs):
        if in_data.get('hoge_date') is None:
            in_data.pop('hoge_date', None)
        return in_data
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1