django-ninja
django-ninja copied to clipboard
ModelSchema automatical validation
Is your feature request related to a problem? Please describe. I am currently using the ModelSchema to define the inputs and outputs of the API. This works fine, but it seems that the validators defined in the model are not checked in the API.
class ExampleModel(models.Model):
my_field = models.PositiveIntegerField(validators=[MaxValueValidator(100)])
with the schema:
class ExampleSchema(ModelSchema):
class Config:
model = models.ExampleModel
model_fields = ['id', 'my_field']
and the API:
@api.post('/example')
def create_example(request, payload: schemas.ExampleSchema):
example = models.ExampleModel.objects.create(**payload.dict())
return {'id': example.id}
It is possible to store numbers bigger 100 over this API, as the validators are not checked.
Describe the solution you'd like Would be cool if the validators are automatically checked in the ModelSchema. If that is not possible, what would be the best way to implement this manually per field in my schema?
The biggest problem here is that we cannot call model.clean()
method automatically because you can run your code in async context (and clean is not yet async ready)
maybe as a workaround can be some extra flag that will let users confirm they are in sync contex and want to run model lelve l validaions...
class ExampleSchema(ModelSchema):
class Config:
model = models.ExampleModel
model_fields = ['id', 'my_field']
model_call_clean = True # <<<< some thing like this
Has there been any more thought regarding validation of ModelSchemas?
+1
I've just opted to only using Schema
instead, since I was fairly annoying every time when I define my data and type it with the Schema, it would tell me attribute x is not defined