Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 8 additions & 8 deletions ninja/orm/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,7 @@ def get_schema_field(
description = None
title = None
max_length = None
nullable = False
python_type = None

if field.is_relation:
Expand All @@ -126,8 +127,9 @@ def get_schema_field(

internal_type = field.related_model._meta.pk.get_internal_type()

if not field.concrete and field.auto_created or field.null:
if not field.concrete and field.auto_created or field.null or optional:
default = None
nullable = True

alias = getattr(field, "get_attname", None) and field.get_attname()

Expand All @@ -147,22 +149,20 @@ def get_schema_field(
internal_type = field.get_internal_type()
python_type = TYPES[internal_type]

if field.primary_key or blank or null or optional:
default = None
nullable = True

if field.has_default():
if callable(field.default):
default_factory = field.default
else:
default = field.default
elif field.primary_key or blank or null:
default = None

if default_factory:
default = PydanticUndefined

if optional:
default = None

if default is None:
default = None
if nullable:
python_type = Union[python_type, None] # aka Optional in 3.7+

description = field.help_text or None
Expand Down
11 changes: 11 additions & 0 deletions tests/test_orm_metaclass.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,7 @@ class OptModel(models.Model):
title = models.CharField()
other = models.CharField(null=True)
extra = models.IntegerField()
count = models.IntegerField(default=0, null=True)

class Meta:
app_label = "tests"
Expand All @@ -124,6 +125,11 @@ class Meta:
"title": {"anyOf": [{"type": "string"}, {"type": "null"}], "title": "Title"},
"other": {"anyOf": [{"type": "string"}, {"type": "null"}], "title": "Other"},
"extra": {"title": "Extra", "type": "integer"},
"count": {
"anyOf": [{"type": "integer"}, {"type": "null"}],
"default": 0,
"title": "Count",
},
}

assert OptSchema2.json_schema().get("required") is None
Expand All @@ -132,6 +138,11 @@ class Meta:
"title": {"anyOf": [{"type": "string"}, {"type": "null"}], "title": "Title"},
"other": {"anyOf": [{"type": "string"}, {"type": "null"}], "title": "Other"},
"extra": {"anyOf": [{"type": "integer"}, {"type": "null"}], "title": "Extra"},
"count": {
"anyOf": [{"type": "integer"}, {"type": "null"}],
"default": 0,
"title": "Count",
},
}


Expand Down