From 0a0d8341a8955a36f6710395a0b7256e47afc434 Mon Sep 17 00:00:00 2001 From: Bryan Kristiono <15132982+Kristinus@users.noreply.github.com> Date: Thu, 24 Aug 2023 12:35:00 -0400 Subject: [PATCH 1/2] Include Enum to NinjaJSONEncoder --- ninja/responses.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/ninja/responses.py b/ninja/responses.py index 440e98c51..557e894ee 100644 --- a/ninja/responses.py +++ b/ninja/responses.py @@ -1,5 +1,6 @@ from ipaddress import IPv4Address, IPv6Address from typing import Any, FrozenSet +from enum import Enum from django.core.serializers.json import DjangoJSONEncoder from django.http import JsonResponse @@ -22,6 +23,8 @@ def default(self, o: Any) -> Any: return o.model_dump() if isinstance(o, (IPv4Address, IPv6Address)): return str(o) + if isinstance(o, Enum): + return str(o) return super().default(o) From feac322aecefaa5b365c67c2d0167d6e80cb390a Mon Sep 17 00:00:00 2001 From: Bryan Kristiono <15132982+Kristinus@users.noreply.github.com> Date: Fri, 25 Aug 2023 10:14:43 -0400 Subject: [PATCH 2/2] add test --- ninja/responses.py | 2 +- tests/test_response.py | 13 +++++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/ninja/responses.py b/ninja/responses.py index 557e894ee..babd366e6 100644 --- a/ninja/responses.py +++ b/ninja/responses.py @@ -1,6 +1,6 @@ +from enum import Enum from ipaddress import IPv4Address, IPv6Address from typing import Any, FrozenSet -from enum import Enum from django.core.serializers.json import DjangoJSONEncoder from django.http import JsonResponse diff --git a/tests/test_response.py b/tests/test_response.py index 0ef0986b2..688186e64 100644 --- a/tests/test_response.py +++ b/tests/test_response.py @@ -1,4 +1,5 @@ import json +from enum import Enum from ipaddress import IPv4Address, IPv6Address from typing import List, Union @@ -30,6 +31,11 @@ def __init__(self, id, user_name, password): self.password = password +class MyEnum(Enum): + first = "first" + second = "second" + + def to_camel(string: str) -> str: return "".join(word.capitalize() for word in string.split("_")) @@ -157,3 +163,10 @@ def test_ipv6address_encoding(): response = Response(data) response_data = json.loads(response.content) assert response_data["ipv6"] == str(data["ipv6"]) + + +def test_enum_encoding(): + data = {"enum": MyEnum.first} + response = Response(data) + response_data = json.loads(response.content) + assert response_data["enum"] == str(data["enum"])