mirror of
https://github.com/fastapi/sqlmodel.git
synced 2026-01-07 01:50:01 -06:00
🐛 Fix auto detecting and setting nullable, allowing overrides in field (#423)
Co-authored-by: Benjamin Rapaport <br@getallstreet.com> Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
This commit is contained in:
committed by
GitHub
parent
85f5e7fc45
commit
ae144e0a39
@@ -423,11 +423,13 @@ def get_column_from_field(field: ModelField) -> Column: # type: ignore
|
||||
index = getattr(field.field_info, "index", Undefined)
|
||||
if index is Undefined:
|
||||
index = False
|
||||
nullable = not primary_key and _is_field_noneable(field)
|
||||
# Override derived nullability if the nullable property is set explicitly
|
||||
# on the field
|
||||
if hasattr(field.field_info, "nullable"):
|
||||
field_nullable = getattr(field.field_info, "nullable")
|
||||
if field_nullable != Undefined:
|
||||
nullable = field_nullable
|
||||
nullable = not primary_key and _is_field_nullable(field)
|
||||
args = []
|
||||
foreign_key = getattr(field.field_info, "foreign_key", None)
|
||||
unique = getattr(field.field_info, "unique", False)
|
||||
@@ -644,11 +646,10 @@ class SQLModel(BaseModel, metaclass=SQLModelMetaclass, registry=default_registry
|
||||
return cls.__name__.lower()
|
||||
|
||||
|
||||
def _is_field_nullable(field: ModelField) -> bool:
|
||||
def _is_field_noneable(field: ModelField) -> bool:
|
||||
if not field.required:
|
||||
# Taken from [Pydantic](https://github.com/samuelcolvin/pydantic/blob/v1.8.2/pydantic/fields.py#L946-L947)
|
||||
is_optional = field.allow_none and (
|
||||
return field.allow_none and (
|
||||
field.shape != SHAPE_SINGLETON or not field.sub_fields
|
||||
)
|
||||
return is_optional and field.default is None and field.default_factory is None
|
||||
return False
|
||||
|
||||
Reference in New Issue
Block a user