django-ninja icon indicating copy to clipboard operation
django-ninja copied to clipboard

[BUG] Optional Not Respected on ModelSchema Fields

Open tspanos opened this issue 3 years ago • 2 comments
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.

image

Versions:

  • Python version: 3.10
  • Django version: 4.0
  • Django-Ninja version: 0.18.0
  • Pydantic Version: 1.9.1

tspanos avatar Jun 14 '22 02:06 tspanos

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]] = []

vitalik avatar Jun 14 '22 08:06 vitalik

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.

boxed avatar Oct 17 '22 11:10 boxed