Skip to content

Avoided that an empty attributes dict is rendered #1196

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Dec 28, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
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
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
4 changes: 3 additions & 1 deletion example/tests/unit/test_renderers.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand 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"]


Expand All @@ -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}
Expand Down
4 changes: 3 additions & 1 deletion rest_framework_json_api/renderers.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down