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

Fix for Issue #16, Issue #6, plus some extra #18

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
Open
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
4 changes: 2 additions & 2 deletions .github/workflows/publish.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ jobs:
- name: Set up Python
uses: actions/setup-python@v2
with:
python-version: "3.8"
- uses: actions/cache@v2
python-version: "3.9"
- uses: actions/cache@v4
name: Configure pip caching
with:
path: ~/.cache/pip
Expand Down
4 changes: 2 additions & 2 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,14 @@ jobs:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ["3.8", "3.9", "3.10", "3.11", "3.12"]
python-version: ["3.9", "3.10", "3.11", "3.12", "3.13"]
steps:
- uses: actions/checkout@v2
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v2
with:
python-version: ${{ matrix.python-version }}
- uses: actions/cache@v2
- uses: actions/cache@v4
name: Configure pip caching
with:
path: ~/.cache/pip
Expand Down
25 changes: 12 additions & 13 deletions djantic/fields.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import logging
import typing
from datetime import date, datetime, time, timedelta
from decimal import Decimal
from enum import Enum
from typing import Any, Dict, List, Union, Optional
import typing
from typing import Any, Dict, List, Optional, Union
from uuid import UUID

from django.utils.functional import Promise
Expand Down Expand Up @@ -200,17 +200,16 @@ def ModelSchemaField(field: Any, schema_name: str) -> tuple:
max_length=max_length,
)

field_is_optional = all([
getattr(field, "null", None),
field.is_relation,
# A list that is null, is the empty list. So there is no need
# to make it nullable.
typing.get_origin(python_type) is not list
])
field_is_optional = all(
[
getattr(field, "null", None),
field.is_relation,
# A list that is null, is the empty list. So there is no need
# to make it nullable.
typing.get_origin(python_type) is not list,
]
)
if field_is_optional:
python_type = Optional[python_type]

return (
python_type,
field_info
)
return (python_type, field_info)
20 changes: 10 additions & 10 deletions djantic/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,6 @@ def __new__(mcs, name: str, bases: tuple, namespace: dict, **kwargs):
and issubclass(base, ModelSchema)
and base == ModelSchema
):

config = namespace["model_config"]
include = config.get("include", None)
exclude = config.get("exclude", None)
Expand All @@ -74,7 +73,7 @@ def __new__(mcs, name: str, bases: tuple, namespace: dict, **kwargs):
raise PydanticUserError(
f'{exc} (Is `model_config["model"]` a valid Django model class?)',
code="class-not-valid",
)
) from exc

if include == "__annotations__":
include = list(annotations.keys())
Expand Down Expand Up @@ -103,7 +102,6 @@ def __new__(mcs, name: str, bases: tuple, namespace: dict, **kwargs):
python_type = None
pydantic_field = None
if field_name in annotations and field_name in namespace:

python_type = annotations.pop(field_name)
pydantic_field = namespace[field_name]
if (
Expand Down Expand Up @@ -143,10 +141,10 @@ def __new__(mcs, name: str, bases: tuple, namespace: dict, **kwargs):
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)
(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)
)


Expand Down Expand Up @@ -221,7 +219,9 @@ def dict(self) -> dict:
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)
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)
Expand All @@ -232,7 +232,6 @@ def dict(self) -> dict:


class ModelSchema(BaseModel, metaclass=ModelSchemaMetaclass):

def __eq__(self, other: Any) -> bool:
result = super().__eq__(other)
if isinstance(result, bool):
Expand Down Expand Up @@ -276,7 +275,8 @@ def from_orm(cls, *args, **kwargs):
return cls.from_django(*args, **kwargs)

@classmethod
def from_django(cls, objs, many=False, context={}):
def from_django(cls, objs, many=False, context=None):
context = context or {}
if many:
result_objs = []
for obj in objs:
Expand Down
4 changes: 2 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@ license = "MIT"
packages = [{ include = "djantic" }]

[tool.poetry.dependencies]
python = "^3.8"
pydantic = "^2.6.2"
python = "^3.9"
Django = ">3,<6"
pydantic = "^2.6.2"

[tool.poetry.group.dev.dependencies]
ruff = "^0.3.7"
Expand Down
9 changes: 9 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import pytest
from packaging import version


@pytest.fixture(scope="session")
def pydantic_version() -> version.Version:
import pydantic

return version.parse(pydantic.VERSION)
Loading
Loading