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
Next Next commit
handle zero as valid pk/id in get_resource_id util method
- update tests to include cases where ID is zero
  • Loading branch information
humayunah committed Jul 22, 2024
commit 928569eba2ae0f98dfd67f6282b296d245e6d358
1 change: 1 addition & 0 deletions AUTHORS
Original file line number Diff line number Diff line change
Expand Up @@ -52,3 +52,4 @@ Tim Selman <timcbaoth@gmail.com>
Tom Glowka <glowka.tom@gmail.com>
Ulrich Schuster <ulrich.schuster@mailworks.org>
Yaniv Peer <yanivpeer@gmail.com>
Humayun Ahmad <humayunahbh@gmail.com>
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ any parts of the framework not mentioned in the documentation should generally b

* Allow overwriting of url field again (regression since 7.0.0)
* Ensured that no fields are rendered when sparse fields is set to an empty value. (regression since 7.0.0)
* Handled zero as a valid ID in `get_resource_id` function.

## [7.0.1] - 2024-06-06

Expand Down
10 changes: 6 additions & 4 deletions rest_framework_json_api/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -307,12 +307,14 @@ def get_resource_type_from_serializer(serializer):
def get_resource_id(resource_instance, resource):
"""Returns the resource identifier for a given instance (`id` takes priority over `pk`)."""
if resource and "id" in resource:
return resource["id"] and encoding.force_str(resource["id"]) or None
return (
encoding.force_str(resource["id"]) if resource["id"] is not None else None
)
if resource_instance:
return (
hasattr(resource_instance, "pk")
and encoding.force_str(resource_instance.pk)
or None
encoding.force_str(resource_instance.pk)
if hasattr(resource_instance, "pk") and resource_instance.pk is not None
else None
)
return None

Expand Down
7 changes: 7 additions & 0 deletions tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -403,6 +403,13 @@ class SerializerWithoutResourceName(serializers.Serializer):
(None, {"id": 11}, "11"),
(object(), {"pk": 11}, None),
(BasicModel(id=6), {"id": 11}, "11"),
(BasicModel(id=0), None, "0"),
(None, {"id": 0}, "0"),
(
BasicModel(id=0),
{"id": 0},
"0",
),
],
)
def test_get_resource_id(resource_instance, resource, expected):
Expand Down