Skip to content

Handle zero as valid pk/id in get_resource_id util method #1245

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
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
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
Loading