jazzband / jsonmodels

jsonmodels is library to make it easier for you to deal with structures that are converted to, or read from JSON.
http://jsonmodels.readthedocs.org/en/latest/
BSD 3-Clause "New" or "Revised" License
334 stars 51 forks source link

Defer validation when setting a value to an EmbeddedField #98

Open avrahamshukron opened 6 years ago

avrahamshukron commented 6 years ago

Consider the following model:

class DatabaseConfig(Base):
    base_url = fields.StringField(required=True)
    db_name = fields.StringField(required=True)

class Config(Base):
    db = EmbeddedField(DatabaseConfig, required=True)

I can create an empty instance of Config, that I can populate with values until validation is required:

conf = Config()
db = DatabaseConfig()

At this point I can assign values to all the fields of db, But I cannot assign db itself to the corresponding field in config:

In [12]: conf.db = db
ValidationError: ("Error for field 'db'.", ValidationError("Error for field 'base_url'.", ValidationError('Field is required!',)))

While I understand why this is happening (fields validates values on assignment in __set__, and in the case of EmbeddedField this means calling validate on the embedded field), this is very annoying since I have to pre-initialize all the embedded fields beforehand.

I think it would be better to defer the validation of EmbeddedField until validate is called on the containing model.