Django, выбор в пользу Serilize

У меня есть такие варианты в моем choices.py


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



Я хочу получить результат в формате json из APIVIEW, используя метод get

Есть ли решение?

Спасибо


{
  "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'),
]
Вернуться на верх