Skip to content

Commit

Permalink
handle zero as valid pk/id in get_resource_id util method
Browse files Browse the repository at this point in the history
- update tests to include cases where ID is zero
  • Loading branch information
humayunah committed Jul 22, 2024
1 parent 6eff72e commit 928569e
Show file tree
Hide file tree
Showing 4 changed files with 15 additions and 4 deletions.
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 <[email protected]>
Tom Glowka <[email protected]>
Ulrich Schuster <[email protected]>
Yaniv Peer <[email protected]>
Humayun Ahmad <[email protected]>
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

0 comments on commit 928569e

Please sign in to comment.