Skip to content

Commit 4cbd66e

Browse files
committed
Lint.
Run the ruff linter over the code as configured by pyproject.toml.
1 parent 0fe023b commit 4cbd66e

File tree

10 files changed

+60
-61
lines changed

10 files changed

+60
-61
lines changed

djantic/fields.py

Lines changed: 12 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
import logging
2+
import typing
23
from datetime import date, datetime, time, timedelta
34
from decimal import Decimal
45
from enum import Enum
5-
from typing import Any, Dict, List, Union, Optional
6-
import typing
6+
from typing import Any, Dict, List, Optional, Union
77
from uuid import UUID
88

99
from django.utils.functional import Promise
@@ -200,17 +200,16 @@ def ModelSchemaField(field: Any, schema_name: str) -> tuple:
200200
max_length=max_length,
201201
)
202202

203-
field_is_optional = all([
204-
getattr(field, "null", None),
205-
field.is_relation,
206-
# A list that is null, is the empty list. So there is no need
207-
# to make it nullable.
208-
typing.get_origin(python_type) is not list
209-
])
203+
field_is_optional = all(
204+
[
205+
getattr(field, "null", None),
206+
field.is_relation,
207+
# A list that is null, is the empty list. So there is no need
208+
# to make it nullable.
209+
typing.get_origin(python_type) is not list,
210+
]
211+
)
210212
if field_is_optional:
211213
python_type = Optional[python_type]
212214

213-
return (
214-
python_type,
215-
field_info
216-
)
215+
return (python_type, field_info)

djantic/main.py

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,7 @@
33
from enum import Enum
44
from functools import reduce
55
from itertools import chain
6-
from typing import Any, Dict, List, Optional, no_type_check, Union
7-
from typing_extensions import get_origin, get_args
6+
from typing import Any, Dict, List, Optional, Union, no_type_check
87

98
from django.core.serializers.json import DjangoJSONEncoder
109
from django.db.models import Manager, Model
@@ -13,8 +12,9 @@
1312
from django.utils.encoding import force_str
1413
from django.utils.functional import Promise
1514
from pydantic import BaseModel, create_model
16-
from pydantic.errors import PydanticUserError
1715
from pydantic._internal._model_construction import ModelMetaclass
16+
from pydantic.errors import PydanticUserError
17+
from typing_extensions import get_args, get_origin
1818

1919
if sys.version_info >= (3, 10):
2020
from types import UnionType
@@ -54,7 +54,6 @@ def __new__(mcs, name: str, bases: tuple, namespace: dict, **kwargs):
5454
and issubclass(base, ModelSchema)
5555
and base == ModelSchema
5656
):
57-
5857
config = namespace["model_config"]
5958
include = config.get("include", None)
6059
exclude = config.get("exclude", None)
@@ -103,7 +102,6 @@ def __new__(mcs, name: str, bases: tuple, namespace: dict, **kwargs):
103102
python_type = None
104103
pydantic_field = None
105104
if field_name in annotations and field_name in namespace:
106-
107105
python_type = annotations.pop(field_name)
108106
pydantic_field = namespace[field_name]
109107
if (
@@ -143,10 +141,10 @@ def __new__(mcs, name: str, bases: tuple, namespace: dict, **kwargs):
143141
def _is_optional_field(annotation) -> bool:
144142
args = get_args(annotation)
145143
return (
146-
(get_origin(annotation) is Union or get_origin(annotation) is UnionType)
147-
and type(None) in args
148-
and len(args) == 2
149-
and any(inspect.isclass(arg) and issubclass(arg, ModelSchema) for arg in args)
144+
(get_origin(annotation) is Union or get_origin(annotation) is UnionType)
145+
and type(None) in args
146+
and len(args) == 2
147+
and any(inspect.isclass(arg) and issubclass(arg, ModelSchema) for arg in args)
150148
)
151149

152150

@@ -221,7 +219,9 @@ def dict(self) -> dict:
221219
non_none_type_annotation = next(
222220
arg for arg in get_args(annotation) if arg is not type(None)
223221
)
224-
data[key] = self._get_annotation_objects(value, non_none_type_annotation)
222+
data[key] = self._get_annotation_objects(
223+
value, non_none_type_annotation
224+
)
225225

226226
elif inspect.isclass(annotation) and issubclass(annotation, ModelSchema):
227227
data[key] = self._get_annotation_objects(self.get(key), annotation)
@@ -232,7 +232,6 @@ def dict(self) -> dict:
232232

233233

234234
class ModelSchema(BaseModel, metaclass=ModelSchemaMetaclass):
235-
236235
def __eq__(self, other: Any) -> bool:
237236
result = super().__eq__(other)
238237
if isinstance(result, bool):

tests/test_fields.py

Lines changed: 20 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,22 @@
11
from typing import Optional
22

33
import pytest
4-
from pydantic import ConfigDict
5-
from testapp.models import Configuration, Listing, Preference, Record, Searchable, User, NullableChar, NullableFK
6-
4+
from packaging import version
75
from pydantic import (
6+
ConfigDict,
7+
ValidationError,
88
ValidationInfo,
99
field_validator,
10-
ValidationError,
10+
)
11+
from testapp.models import (
12+
Configuration,
13+
Listing,
14+
NullableChar,
15+
NullableFK,
16+
Preference,
17+
Record,
18+
Searchable,
19+
User,
1120
)
1221

1322
from djantic import ModelSchema
@@ -43,25 +52,21 @@ class UserSchema(ModelSchema):
4352

4453
@pytest.mark.django_db
4554
def test_context_for_field():
46-
4755
def get_context():
48-
return {'check_title': lambda x: x.istitle()}
56+
return {"check_title": lambda x: x.istitle()}
4957

5058
class UserSchema(ModelSchema):
51-
model_config = ConfigDict(
52-
model=User,
53-
revalidate_instances='always'
54-
)
59+
model_config = ConfigDict(model=User, revalidate_instances="always")
5560

56-
@field_validator('first_name', mode="before", check_fields=False)
61+
@field_validator("first_name", mode="before", check_fields=False)
5762
@classmethod
5863
def validate_first_name(cls, v: str, info: ValidationInfo):
5964
if not info.context:
6065
return v
6166

62-
check_title = info.context.get('check_title')
67+
check_title = info.context.get("check_title")
6368
if check_title and not check_title(v):
64-
raise ValueError('First name needs to be a title')
69+
raise ValueError("First name needs to be a title")
6570
return v
6671

6772
user = User.objects.create(first_name="hello", email="a@a.com")
@@ -533,11 +538,11 @@ class ListingSchema(ModelSchema):
533538
@pytest.mark.django_db
534539
def test_nullable_fk():
535540
class NullableCharSchema(ModelSchema):
536-
model_config = ConfigDict(model=NullableChar, include='value')
541+
model_config = ConfigDict(model=NullableChar, include="value")
537542

538543
class NullableFKSchema(ModelSchema):
539544
nullable_char: Optional[NullableCharSchema] = None
540-
model_config = ConfigDict(model=NullableFK, include='nullable_char')
545+
model_config = ConfigDict(model=NullableFK, include="nullable_char")
541546

542547
nullable_char = NullableChar(value="test")
543548
nullable_char.save()

tests/test_files.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
from tempfile import NamedTemporaryFile
22

33
import pytest
4+
from pydantic import ConfigDict
45
from testapp.models import Attachment
56

6-
from pydantic import ConfigDict
77
from djantic import ModelSchema
88

99

tests/test_main.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
import pytest
2+
from pydantic import ConfigDict
23
from pydantic.errors import PydanticUserError
34
from testapp.models import User
45

5-
from pydantic import ConfigDict
66
from djantic import ModelSchema
77

88

tests/test_queries.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
from typing import List
22

33
import pytest
4+
from pydantic import ConfigDict
45
from testapp.models import Bookmark, Message, Profile, Tagged, Thread, User
56

6-
from pydantic import ConfigDict
77
from djantic import ModelSchema
88

99

@@ -28,15 +28,13 @@ class UserSchema(ModelSchema):
2828

2929
@pytest.mark.django_db
3030
def test_get_instance_with_generic_foreign_key():
31-
3231
bookmark = Bookmark.objects.create(url="https://www.djangoproject.com/")
3332
Tagged.objects.create(content_object=bookmark, slug="django")
3433

3534
class TaggedSchema(ModelSchema):
3635
model_config = ConfigDict(model=Tagged)
3736

3837
class BookmarkWithTaggedSchema(ModelSchema):
39-
4038
tags: List[TaggedSchema]
4139
model_config = ConfigDict(model=Bookmark)
4240

@@ -222,7 +220,6 @@ class ThreadWithMessageListSchema(ModelSchema):
222220

223221
@pytest.mark.django_db
224222
def test_get_queryset_with_generic_foreign_key():
225-
226223
bookmark = Bookmark.objects.create(url="https://github.com")
227224
bookmark.tags.create(slug="tag-1")
228225
bookmark.tags.create(slug="tag-2")

tests/test_relations.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
from typing import Dict, List, Optional
33

44
import pytest
5-
from pydantic import Field
5+
from pydantic import ConfigDict, Field
66
from testapp.models import (
77
Article,
88
Bookmark,
@@ -17,7 +17,6 @@
1717
User,
1818
)
1919

20-
from pydantic import ConfigDict
2120
from djantic import ModelSchema
2221

2322

@@ -656,7 +655,6 @@ class BookmarkSchema(ModelSchema):
656655
}
657656

658657
class BookmarkWithTaggedSchema(ModelSchema):
659-
660658
tags: List[TaggedSchema]
661659
model_config = ConfigDict(model=Bookmark)
662660

@@ -724,7 +722,6 @@ class BookmarkWithTaggedSchema(ModelSchema):
724722
}
725723

726724
class ItemSchema(ModelSchema):
727-
728725
tags: List[TaggedSchema]
729726
model_config = ConfigDict(model=Item)
730727

tests/test_schemas.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,9 @@
22
from typing import Optional
33

44
import pytest
5-
from pydantic import BaseModel, Field
5+
from pydantic import AliasGenerator, BaseModel, ConfigDict, Field
6+
from testapp.models import Profile, User
67

7-
from testapp.models import User, Profile, Configuration
8-
9-
from pydantic import ConfigDict, AliasGenerator
108
from djantic import ModelSchema
119

1210

tests/testapp/manage.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
#!/usr/bin/env python
22
"""Django's command-line utility for administrative tasks."""
3+
34
import os
45
import sys
56

tests/testapp/models.py

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,14 @@
1-
import uuid
21
import os.path
2+
import uuid
33
from typing import Optional
44

5-
from django.contrib.contenttypes.fields import GenericForeignKey
5+
from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
66
from django.contrib.contenttypes.models import ContentType
7-
from django.contrib.contenttypes.fields import GenericRelation
8-
from django.db import models
9-
from django.utils.text import slugify
10-
from django.contrib.postgres.fields import JSONField, ArrayField
7+
from django.contrib.postgres.fields import ArrayField, JSONField
118
from django.contrib.postgres.indexes import GinIndex
129
from django.contrib.postgres.search import SearchVectorField
10+
from django.db import models
11+
from django.utils.text import slugify
1312
from django.utils.translation import gettext_lazy as _
1413

1514
from .fields import ListField, NotNullRestrictedCharField
@@ -281,12 +280,16 @@ class Case(ExtendedModel):
281280

282281
class Listing(models.Model):
283282
items = ArrayField(models.TextField(), size=4)
284-
content_type = models.ForeignKey(ContentType, on_delete=models.PROTECT, blank=True, null=True)
283+
content_type = models.ForeignKey(
284+
ContentType, on_delete=models.PROTECT, blank=True, null=True
285+
)
285286

286287

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

290291

291292
class NullableFK(models.Model):
292-
nullable_char = models.ForeignKey(NullableChar, null=True, blank=True, on_delete=models.CASCADE)
293+
nullable_char = models.ForeignKey(
294+
NullableChar, null=True, blank=True, on_delete=models.CASCADE
295+
)

0 commit comments

Comments
 (0)