1132 If a column is nullable, make it optional by default in create_pydantic_model#1141
1132 If a column is nullable, make it optional by default in create_pydantic_model#1141dantownsend wants to merge 2 commits intomasterfrom
create_pydantic_model#1141Conversation
|
Assuming |
|
I agree with these changes and everything works, but we have one case where someone makes a mistake and marks a null field as optional. We have four options. class Band(Table):
name = Varchar() # null=False by default
>>> create_pydantic_model(Band).model_fields['name'].annotation
str # correct
class Band(Table):
name = Varchar(null=True)
>>> create_pydantic_model(Band).model_fields['name'].annotation
Optional[str] # correct
class Band(Table):
name = Varchar(required=True, null=True)
>>> create_pydantic_model(Band).model_fields['name'].annotation
str # correct
class Band(Table):
name = Varchar(required=False) # null=False by default
>>> create_pydantic_model(Band).model_fields['name'].annotation
Optional[str] # not correct, should be str (required because is not null constraint in db)Should we prevent these possible user errors or not? If we change this line of code, we can force class Band(Table):
name = Varchar(required=False) # null=False by default
>>> create_pydantic_model(Band).model_fields['name'].annotation
str # correctwhich is correct. |
|
@Skelmis and @sinisaos - thanks for your feedback on this. I've been thinking about it today, and I'm a bit undecided still. Current behaviourThe current behaviour in Piccolo is class Band(Table):
name = Varchar()The it generates the following Pydantic model: class BandModel(BaseModel):
name: Optional[str]In terms of generating the Pydantic model, This is similar to Django where they have Maybe we should have made Multiple Pydantic modelsThe downside with putting
We get around 1 by having the create_pydantic_model(
Band,
all_optional=True
)If someone required even more Pydantic models from the same Piccolo table it gets tricky. Perhaps there could be a create_pydantic_model(
Band,
required_columns=Band.all_columns(exclude=[Band.some_column])
)That gives the ultimate flexibility. Conclusions (?)I'm still a bit on the fence ... I'm interested to hear your thoughts. I think I'll refactor piccolo-orm/piccolo_admin#432 slightly for now, so it's decoupled from this PR, as I don't want to rush this in and make a mistake. |
@sinisaos I think for that situation we just assume that the user will add the missing value before saving it to the database. |
Resolves #1132