django-ninja
django-ninja copied to clipboard
[BUG] Optional Not Respected on ModelSchema Fields
trafficstars
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.

Versions:
- Python version: 3.10
- Django version: 4.0
- Django-Ninja version: 0.18.0
- Pydantic Version: 1.9.1
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]] = []
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.