Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit e315d86

Browse files
Peter Kajanmartinsmid
Peter Kajan
authored andcommitted
Add optional type checking to ResourceIdentifierSerialiser
1 parent bc581a1 commit e315d86

File tree

1 file changed

+14
-0
lines changed

1 file changed

+14
-0
lines changed

‎rest_framework_json_api/serializers.py‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,10 +21,24 @@ class ResourceIdentifierSerializer(Serializer):
2121
id = CharField(max_length=64)
2222
type = CharField(max_length=256)
2323

24+
default_error_messages = {
25+
'wrong_type': _('Expected resource of following types: {expected_types}. Got {received_type}.'),
26+
}
27+
28+
def __init__(self, *args, **kwargs):
29+
self.expected_types = kwargs.pop('expected_types', None)
30+
super(ResourceIdentifierSerializer, self).__init__(*args, **kwargs)
31+
2432
def to_internal_value(self, data):
2533
ret = super(ResourceIdentifierSerializer, self).to_internal_value(data)
2634
return ResourceIdentifier(ret['type'], ret['id'])
2735

36+
def validate_type(self, resource_type):
37+
if self.expected_types is not None and resource_type not in self.expected_types:
38+
raise ValidationError(self.error_messages['wrong_type'].format(expected_types=self.expected_types,
39+
received_type=resource_type))
40+
return resource_type
41+
2842

2943
class ResourceIdentifierObjectSerializer(BaseSerializer):
3044
default_error_messages = {

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /