diff --git a/CHANGELOG.md b/CHANGELOG.md index 9664124c..f64e70ba 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,8 @@ any parts of the framework not mentioned in the documentation should generally b * Fixed OpenAPI schema generation for `Serializer` when used inside another `Serializer` or as a child of `ListField`. * `ModelSerializer` fields are now returned in the same order than DRF +* Avoided that an empty attributes dict is rendered in case serializer does not + provide any attribute fields. ### Removed diff --git a/example/tests/unit/test_renderers.py b/example/tests/unit/test_renderers.py index 00eaf28b..f34ce8d6 100644 --- a/example/tests/unit/test_renderers.py +++ b/example/tests/unit/test_renderers.py @@ -126,7 +126,7 @@ class WriteonlyTestSerializer(serializers.ModelSerializer): class Meta: model = Entry - fields = ("comments", "rating") + fields = ("headline", "comments", "rating") class WriteOnlyDummyTestViewSet(views.ReadOnlyModelViewSet): queryset = Entry.objects.all() @@ -136,6 +136,7 @@ class WriteOnlyDummyTestViewSet(views.ReadOnlyModelViewSet): result = json.loads(rendered.decode()) assert "rating" not in result["data"]["attributes"] + assert "headline" in result["data"]["attributes"] assert "relationships" not in result["data"] @@ -153,6 +154,7 @@ class EmptyRelationshipViewSet(views.ReadOnlyModelViewSet): rendered = render_dummy_test_serialized_view(EmptyRelationshipViewSet, Author()) result = json.loads(rendered.decode()) + assert "attributes" not in result["data"] assert "relationships" in result["data"] assert "bio" in result["data"]["relationships"] assert result["data"]["relationships"]["bio"] == {"data": None} diff --git a/rest_framework_json_api/renderers.py b/rest_framework_json_api/renderers.py index b065af5b..0664f73a 100644 --- a/rest_framework_json_api/renderers.py +++ b/rest_framework_json_api/renderers.py @@ -452,8 +452,10 @@ def build_json_resource_obj( resource_data = { "type": resource_name, "id": utils.get_resource_id(resource_instance, resource), - "attributes": cls.extract_attributes(fields, resource), } + attributes = cls.extract_attributes(fields, resource) + if attributes: + resource_data["attributes"] = attributes relationships = cls.extract_relationships(fields, resource, resource_instance) if relationships: resource_data["relationships"] = relationships