Skip to content

Commit

Permalink
Handle zero as valid pk/id in get_resource_id util method (#1245)
Browse files Browse the repository at this point in the history
---------

Co-authored-by: Oliver Sauder <[email protected]>
  • Loading branch information
humayunah and sliverc authored Jul 23, 2024
1 parent 6eff72e commit 75a5424
Show file tree
Hide file tree
Showing 4 changed files with 18 additions and 6 deletions.
1 change: 1 addition & 0 deletions AUTHORS
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ David Guillot, for Contexte <[email protected]>
David Vogt <[email protected]>
Felix Viernickel <[email protected]>
Greg Aker <[email protected]>
Humayun Ahmad <[email protected]>
Jamie Bliss <[email protected]>
Jason Housley <[email protected]>
Jeppe Fihl-Pearson <[email protected]>
Expand Down
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
Note that in line with [Django REST framework policy](https://www.django-rest-framework.org/topics/release-notes/),
any parts of the framework not mentioned in the documentation should generally be considered private API, and may be subject to change.

## [Unreleased]

### Fixed

* Handled zero as a valid ID for resource (regression since 6.1.0)

## [7.0.2] - 2024-06-28

### Fixed
Expand Down
10 changes: 4 additions & 6 deletions rest_framework_json_api/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -307,13 +307,11 @@ 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
_id = resource["id"]
return encoding.force_str(_id) if _id is not None else None
if resource_instance:
return (
hasattr(resource_instance, "pk")
and encoding.force_str(resource_instance.pk)
or None
)
pk = getattr(resource_instance, "pk", None)
return encoding.force_str(pk) if 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 75a5424

Please sign in to comment.