vitalik / django-ninja

💨 Fast, Async-ready, Openapi, type hints based framework for building APIs
https://django-ninja.dev
MIT License
7.23k stars 429 forks source link

[BUG] Optional Not Respected on ModelSchema Fields #472

Open tspanos opened 2 years ago

tspanos commented 2 years ago

Describe the bug Assume the following Model and ModelSchema:

class Car(models.Model):
    car_model = models.CharField(max_length=120)
    year = models.IntegerField()
    vin_number = models.CharField(max_length=17)
    manufacturer = models.ForeignKey(to='Manufacturer', on_delete=models.CASCADE)
    drivers = models.ManyToManyField(to='Driver')
class CarSchemaIn(ModelSchema):
    manufacturer: Optional[ManufacturerSchemaIn]
    manufacturer_id: Optional[int]
    drivers: Optional[List[DriverSchemaIn]]
    drivers_ids: Optional[List[int]]

    class Config:
        model = models.Car
        model_fields = ['car_model', 'year', 'vin_number']

django-ninja does not obey the Optional type and generates a schema where the manually declared optional fields are required.

image

Versions:

vitalik commented 2 years ago

Hi @tspanos

for now you can use the following workaround - set Default value for each attr:

class CarSchemaIn(ModelSchema):
    manufacturer: Optional[ManufacturerSchemaIn] = None
    manufacturer_id: Optional[int]= None
    drivers: Optional[List[DriverSchemaIn]] = []
    drivers_ids: Optional[List[int]] = []
boxed commented 2 years ago

This workaround only works if the users sends nothing for the given key? It doesn't work if the client sends null at least. And the generated docs are of course still wrong.