Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow nullable foreign keys #12

Merged
merged 5 commits into from
Jun 27, 2024
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
27 changes: 26 additions & 1 deletion djantic/main.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import inspect
import sys
from enum import Enum
from functools import reduce
from itertools import chain
Expand All @@ -15,6 +16,10 @@
from pydantic.errors import PydanticUserError
from pydantic._internal._model_construction import ModelMetaclass

if sys.version_info >= (3, 10):
from types import UnionType
else:
from typing import Union as UnionType
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@idan-david This looks ok to me. The import on line 6 needs to be removed though. Let's see if the tests pass after this.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry for the mess, removed the import on line 6


from .fields import ModelSchemaField

Expand Down Expand Up @@ -136,6 +141,16 @@ def __new__(mcs, name: str, bases: tuple, namespace: dict, **kwargs):
return cls


def _is_optional_field(annotation) -> bool:
args = get_args(annotation)
return (
(get_origin(annotation) is Union or get_origin(annotation) is UnionType)
and type(None) in args
and len(args) == 2
and any(inspect.isclass(arg) and issubclass(arg, ModelSchema) for arg in args)
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This was causing problems with python 3.9, added the inspect.isclass(arg)

)


class ProxyGetterNestedObj:
def __init__(self, obj: Any, schema_class):
self._obj = obj
Expand Down Expand Up @@ -199,7 +214,17 @@ def dict(self) -> dict:
# Pick the underlying annotation
annotation = get_args(annotation)[0]

if inspect.isclass(annotation) and issubclass(annotation, ModelSchema):
if _is_optional_field(annotation):
value = self.get(key)
if value is None:
data[key] = None
else:
non_none_type_annotation = next(
arg for arg in get_args(annotation) if arg is not type(None)
)
data[key] = self._get_annotation_objects(value, non_none_type_annotation)

elif inspect.isclass(annotation) and issubclass(annotation, ModelSchema):
data[key] = self._get_annotation_objects(self.get(key), annotation)
else:
key = fieldinfo.alias if fieldinfo.alias else key
Expand Down
28 changes: 27 additions & 1 deletion tests/test_fields.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
from typing import Optional

import pytest
from pydantic import ConfigDict
from testapp.models import Configuration, Listing, Preference, Record, Searchable, User
from testapp.models import Configuration, Listing, Preference, Record, Searchable, User, NullableChar, NullableFK

from pydantic import (
ValidationInfo,
Expand Down Expand Up @@ -408,3 +410,27 @@ class ListingSchema(ModelSchema):
"id": None,
"items": ["a", "b"],
}


@pytest.mark.django_db
def test_nullable_fk():
class NullableCharSchema(ModelSchema):
model_config = ConfigDict(model=NullableChar, include='value')

class NullableFKSchema(ModelSchema):
nullable_char: Optional[NullableCharSchema] = None
model_config = ConfigDict(model=NullableFK, include='nullable_char')

nullable_char = NullableChar(value="test")
nullable_char.save()
model = NullableFK(nullable_char=nullable_char)
assert NullableFKSchema.from_django(model).dict() == {
"nullable_char": {
"value": "test"
}
}

model2 = NullableFK(nullable_char=None)
assert NullableFKSchema.from_django(model2).dict() == {
"nullable_char": None
}
8 changes: 8 additions & 0 deletions tests/testapp/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -282,3 +282,11 @@ class Case(ExtendedModel):
class Listing(models.Model):
items = ArrayField(models.TextField(), size=4)
content_type = models.ForeignKey(ContentType, on_delete=models.PROTECT, blank=True, null=True)


class NullableChar(models.Model):
value = models.CharField(max_length=256, null=True, blank=True)


class NullableFK(models.Model):
nullable_char = models.ForeignKey(NullableChar, null=True, blank=True, on_delete=models.CASCADE)
Loading