|
26 | 26 |
|
27 | 27 | from pydantic import BaseModel |
28 | 28 | from pydantic.errors import ConfigError, DictError |
| 29 | +from pydantic.fields import SHAPE_SINGLETON |
29 | 30 | from pydantic.fields import FieldInfo as PydanticFieldInfo |
30 | 31 | from pydantic.fields import ModelField, Undefined, UndefinedType |
31 | 32 | from pydantic.main import BaseConfig, ModelMetaclass, validate_model |
@@ -414,7 +415,7 @@ def get_column_from_field(field: ModelField) -> Column: |
414 | 415 | return sa_column |
415 | 416 | sa_type = get_sqlachemy_type(field) |
416 | 417 | primary_key = getattr(field.field_info, "primary_key", False) |
417 | | - nullable = not field.required |
| 418 | + nullable = not primary_key and _is_field_nullable(field) |
418 | 419 | index = getattr(field.field_info, "index", Undefined) |
419 | 420 | if index is Undefined: |
420 | 421 | index = True |
@@ -634,3 +635,13 @@ def _calculate_keys( # type: ignore |
634 | 635 | @declared_attr # type: ignore |
635 | 636 | def __tablename__(cls) -> str: |
636 | 637 | return cls.__name__.lower() |
| 638 | + |
| 639 | + |
| 640 | +def _is_field_nullable(field: ModelField) -> bool: |
| 641 | + if not field.required: |
| 642 | + # Taken from [Pydantic](https://github.com/samuelcolvin/pydantic/blob/v1.8.2/pydantic/fields.py#L946-L947) |
| 643 | + is_optional = field.allow_none and ( |
| 644 | + field.shape != SHAPE_SINGLETON or not field.sub_fields |
| 645 | + ) |
| 646 | + return is_optional and field.default is None and field.default_factory is None |
| 647 | + return False |
0 commit comments