Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
3 changes: 2 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,9 @@ any parts of the framework not mentioned in the documentation should generally b

### Fixed

* Adjusted error messages to correctly use capitial "JSON:API" abbreviation as used in the specification.
* Adjusted error messages to correctly use capital "JSON:API" abbreviation as used in the specification.
* Avoid error when `parser_context` is `None` while parsing.
* Raise comprehensible error when reserved field names `meta` and `results` are used.

### Changed

Expand Down
19 changes: 19 additions & 0 deletions rest_framework_json_api/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,25 @@ def __repr__(self):


class SerializerMetaclass(SerializerMetaclass):

_reserved_field_names = {"meta", "results"}

@classmethod
def _get_declared_fields(cls, bases, attrs):
fields = super()._get_declared_fields(bases, attrs)

found_reserved_field_names = cls._reserved_field_names.intersection(
fields.keys()
)
if found_reserved_field_names:
raise AttributeError(
f"Serializer class {attrs['__module__']}.{attrs['__qualname__']} uses "
f"following reserved field name(s) which is not allowed: "
f"{', '.join(sorted(found_reserved_field_names))}"
)

return fields

def __new__(cls, name, bases, attrs):
serializer = super().__new__(cls, name, bases, attrs)

Expand Down
15 changes: 15 additions & 0 deletions tests/test_serializers.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import pytest
from django.db import models

from rest_framework_json_api import serializers
Expand Down Expand Up @@ -33,3 +34,17 @@ class Meta:
}

assert included_serializers == expected_included_serializers


def test_reserved_field_names():
with pytest.raises(AttributeError) as e:

class ReservedFieldNamesSerializer(serializers.Serializer):
meta = serializers.CharField()
results = serializers.CharField()

assert str(e.value) == (
"Serializer class tests.test_serializers.test_reserved_field_names.<locals>."
"ReservedFieldNamesSerializer uses following reserved field name(s) which is "
"not allowed: meta, results"
)