Skip to content

Commit 9ed384d

Browse files
committed
Clean-up and test relational fields
1 parent a26b52a commit 9ed384d

File tree

3 files changed

+23
-6
lines changed

3 files changed

+23
-6
lines changed

rest_framework_dataclasses/field_utils.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -72,14 +72,19 @@ def get_type_info(tp: type, default_value_type: typing.Optional[type] = None) ->
7272
return TypeInfo(is_many, is_mapping, is_final, is_optional, tp)
7373

7474

75-
def get_relation_info(definition: DataclassDefinition, type_info: TypeInfo) -> RelationInfo:
76-
# TODO needs checks first
75+
def get_relation_info(type_info: TypeInfo) -> RelationInfo:
76+
"""
77+
Given a type_info that references a Model, extract the RelationInfo.
78+
"""
7779
return RelationInfo(
80+
# there's no foreign key field
7881
model_field=None,
7982
related_model=type_info.base_type,
8083
to_many=type_info.is_many,
84+
# as there's no foreign key, it also cannot reference a field on the referenced model
8185
to_field=None,
8286
has_through_model=False,
87+
# we're never the model
8388
reverse=False
8489
)
8590

rest_framework_dataclasses/serializers.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -404,7 +404,7 @@ def build_relational_field(self, field_name: str, type_info: TypeInfo) -> Serial
404404
"""
405405
Create fields for models.
406406
"""
407-
relation_info = field_utils.get_relation_info(self.dataclass_definition, type_info)
407+
relation_info = field_utils.get_relation_info(type_info)
408408
field_class = self.serializer_related_field
409409
field_kwargs = get_relation_kwargs(field_name, relation_info)
410410

tests/test_fields.py

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,9 @@
88
import uuid
99
from collections import abc
1010

11-
from rest_framework import fields
11+
import django
12+
from django.db import models
13+
from rest_framework import fields, relations
1214

1315
from rest_framework_dataclasses import field_utils
1416
from rest_framework_dataclasses.serializers import DataclassSerializer
@@ -101,8 +103,18 @@ def test_nested(self):
101103
{'dataclass': refclass, 'many': False, 'required': False, 'allow_null': True})
102104

103105
def test_relational(self):
104-
# TODO
105-
pass
106+
django.setup()
107+
108+
class Person(models.Model):
109+
name = models.CharField(max_length=30)
110+
111+
class Meta:
112+
app_label = 'tests'
113+
114+
self.check_field(Person, relations.PrimaryKeyRelatedField,
115+
{'queryset': Person._default_manager})
116+
self.check_field(typing.Optional[Person], relations.PrimaryKeyRelatedField,
117+
{'queryset': Person._default_manager, 'required': False, 'allow_null': True})
106118

107119
def test_literal(self):
108120
self.check_field(Literal['a', 'b'], fields.ChoiceField,

0 commit comments

Comments
 (0)