Django, Choices to Serilize

I have choices like this in my choices.py


MATH_CHOICES_TYPE = (
    ('1', 'test1'),
    ('2', 'teste2'),
    ('3', 'test3'),
    ('4','test4')
)



I want to get result like this as json from APIVIEW using get method

Is there any solution?

Thanks


{
  "MATH_CHOICES_TYPE": [
    {
      "value": "1",
      "display_name": "test1"
    },
    {
      "value": "2",
      "display_name": "test2"
    },
    {
      "value": "3",
      "display_name": "test3"
    },
    {
      "value": "4",
      "display_name": "test4"
    }
  ]
}

math_choices.py

from django.http import JsonResponse

MATH_CHOICES_TYPE = (
    ('1', 'test1'),
    ('2', 'teste2'),
    ('3', 'test3'),
    ('4','test4')
)

# Convert the tuple to a list of dictionaries
math_choices_list = [{"value": choice[0], "display_name": choice[1]} for choice in MATH_CHOICES_TYPE]

math_choices_list = {
"MATH_CHOICES_TYPE" : math_choices_list 
}

return JsonResponse(math_choices_list, safe=False)

urls.py

from django.urls import path

from .views import math_choices

urlpatterns = [
    path('math_choices/', math_choices, name='math_choices'),
]
Back to Top