Skip to content

Commit 928569e

Browse files
committed
handle zero as valid pk/id in get_resource_id util method
- update tests to include cases where ID is zero
1 parent 6eff72e commit 928569e

File tree

4 files changed

+15
-4
lines changed

4 files changed

+15
-4
lines changed

AUTHORS

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,3 +52,4 @@ Tim Selman <timcbaoth@gmail.com>
5252
Tom Glowka <glowka.tom@gmail.com>
5353
Ulrich Schuster <ulrich.schuster@mailworks.org>
5454
Yaniv Peer <yanivpeer@gmail.com>
55+
Humayun Ahmad <humayunahbh@gmail.com>

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ any parts of the framework not mentioned in the documentation should generally b
1414

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

1819
## [7.0.1] - 2024-06-06
1920

rest_framework_json_api/utils.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -307,12 +307,14 @@ 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+
return (
311+
encoding.force_str(resource["id"]) if resource["id"] is not None else None
312+
)
311313
if resource_instance:
312314
return (
313-
hasattr(resource_instance, "pk")
314-
and encoding.force_str(resource_instance.pk)
315-
or None
315+
encoding.force_str(resource_instance.pk)
316+
if hasattr(resource_instance, "pk") and resource_instance.pk is not None
317+
else None
316318
)
317319
return None
318320

tests/test_utils.py

Lines changed: 7 additions & 0 deletions
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)