From 75a5424fb429196675e437889000a9ba40287670 Mon Sep 17 00:00:00 2001 From: Humayun Ahmad Date: Tue, 23 Jul 2024 11:52:45 +0500 Subject: [PATCH] Handle zero as valid pk/id in get_resource_id util method (#1245) --------- Co-authored-by: Oliver Sauder --- AUTHORS | 1 + CHANGELOG.md | 6 ++++++ rest_framework_json_api/utils.py | 10 ++++------ tests/test_utils.py | 7 +++++++ 4 files changed, 18 insertions(+), 6 deletions(-) diff --git a/AUTHORS b/AUTHORS index 7f4a8237..d421d5e6 100644 --- a/AUTHORS +++ b/AUTHORS @@ -15,6 +15,7 @@ David Guillot, for Contexte David Vogt Felix Viernickel Greg Aker +Humayun Ahmad Jamie Bliss Jason Housley Jeppe Fihl-Pearson diff --git a/CHANGELOG.md b/CHANGELOG.md index 8c3c7720..4fb30d1b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/rest_framework_json_api/utils.py b/rest_framework_json_api/utils.py index e12080ac..805f5f09 100644 --- a/rest_framework_json_api/utils.py +++ b/rest_framework_json_api/utils.py @@ -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 diff --git a/tests/test_utils.py b/tests/test_utils.py index 4e103ae2..a3beb12e 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -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):