Skip to content

Commit 75a5424

Browse files
humayunahsliverc
andauthored
Handle zero as valid pk/id in get_resource_id util method (#1245)
--------- Co-authored-by: Oliver Sauder <[email protected]>
1 parent 6eff72e commit 75a5424

File tree

4 files changed

+18
-6
lines changed

4 files changed

+18
-6
lines changed

AUTHORS

+1
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ David Guillot, for Contexte <[email protected]>
1515
David Vogt <[email protected]>
1616
Felix Viernickel <[email protected]>
1717
Greg Aker <[email protected]>
18+
Humayun Ahmad <[email protected]>
1819
Jamie Bliss <[email protected]>
1920
Jason Housley <[email protected]>
2021
Jeppe Fihl-Pearson <[email protected]>

CHANGELOG.md

+6
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
88
Note that in line with [Django REST framework policy](https://www.django-rest-framework.org/topics/release-notes/),
99
any parts of the framework not mentioned in the documentation should generally be considered private API, and may be subject to change.
1010

11+
## [Unreleased]
12+
13+
### Fixed
14+
15+
* Handled zero as a valid ID for resource (regression since 6.1.0)
16+
1117
## [7.0.2] - 2024-06-28
1218

1319
### Fixed

rest_framework_json_api/utils.py

+4-6
Original file line numberDiff line numberDiff line change
@@ -307,13 +307,11 @@ def get_resource_type_from_serializer(serializer):
307307
def get_resource_id(resource_instance, resource):
308308
"""Returns the resource identifier for a given instance (`id` takes priority over `pk`)."""
309309
if resource and "id" in resource:
310-
return resource["id"] and encoding.force_str(resource["id"]) or None
310+
_id = resource["id"]
311+
return encoding.force_str(_id) if _id is not None else None
311312
if resource_instance:
312-
return (
313-
hasattr(resource_instance, "pk")
314-
and encoding.force_str(resource_instance.pk)
315-
or None
316-
)
313+
pk = getattr(resource_instance, "pk", None)
314+
return encoding.force_str(pk) if pk is not None else None
317315
return None
318316

319317

tests/test_utils.py

+7
Original file line numberDiff line numberDiff line change
@@ -403,6 +403,13 @@ class SerializerWithoutResourceName(serializers.Serializer):
403403
(None, {"id": 11}, "11"),
404404
(object(), {"pk": 11}, None),
405405
(BasicModel(id=6), {"id": 11}, "11"),
406+
(BasicModel(id=0), None, "0"),
407+
(None, {"id": 0}, "0"),
408+
(
409+
BasicModel(id=0),
410+
{"id": 0},
411+
"0",
412+
),
406413
],
407414
)
408415
def test_get_resource_id(resource_instance, resource, expected):

0 commit comments

Comments
 (0)