Django,串行化的选择

wfveoks0  于 2023-01-31  发布在  Go
关注(0)|答案(1)|浏览(128)

我在我的www.example.com上有这样的选择choices.py

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

我希望使用get方法从APIVIEW中获得类似于json的结果
有什么办法吗?
谢谢

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

1wnzp6jl1#

数学_选择.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'),
]

相关问题