在 Django 中处理 GET/POST 请求中的多维数组(嵌套数据结构)时,可以使用 Django 的 request.GET
和 request.POST
字典来获取数据。由于 GET 和 POST 数据通常是通过 URL 查询参数或表单数据传递的,处理多维数组需要一些额外的步骤。
假设你有一个 URL 查询参数如下:
/example/?data[0][name]=Alice&data[0][age]=30&data[1][name]=Bob&data[1][age]=25
在 Django 中,你可以使用 request.GET
来获取这些参数。由于 Django 的 QueryDict
不支持直接解析多维数组,你需要手动解析这些参数。
from django.http import JsonResponse
def example_view(request):
data = {}
for key, value in request.GET.items():
if key.startswith('data['):
# Extract the indices and field names
indices = key[5:key.index(']')].split('][')
field_name = key[key.index(']') + 2:]
# Convert indices to integers
indices = [int(index) for index in indices]
# Create nested dictionaries
current_level = data
for index in indices[:-1]:
if index not in current_level:
current_level[index] = {}
current_level = current_level[index]
# Assign the value
current_level[indices[-1]] = {field_name: value}
return JsonResponse(data)
假设你有一个表单数据如下:
data[0][name]=Alice&data[0][age]=30&data[1][name]=Bob&data[1][age]=25
在 Django 中,你可以使用 request.POST
来获取这些参数。处理方式与 GET 请求类似。
from django.http import JsonResponse
def example_view(request):
if request.method == 'POST':
data = {}
for key, value in request.POST.items():
if key.startswith('data['):
# Extract the indices and field names
indices = key[5:key.index(']')].split('][')
field_name = key[key.index(']') + 2:]
# Convert indices to integers
indices = [int(index) for index in indices]
# Create nested dictionaries
current_level = data
for index in indices[:-1]:
if index not in current_level:
current_level[index] = {}
current_level = current_level[index]
# Assign the value
current_level[indices[-1]] = {field_name: value}
return JsonResponse(data)
else:
return JsonResponse({'error': 'Invalid request method'}, status=400)
如果你可以控制前端发送的数据格式,使用 JSON 数据会更方便处理多维数组。你可以在前端将数据序列化为 JSON 格式,并在 Django 中解析 JSON 数据。
const data = [
{ name: 'Alice', age: 30 },
{ name: 'Bob', age: 25 }
];
fetch('/example/', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
});
import json
from django.http import JsonResponse
def example_view(request):
if request.method == 'POST':
try:
data = json.loads(request.body)
return JsonResponse(data)
except json.JSONDecodeError:
return JsonResponse({'error': 'Invalid JSON'}, status=400)
else:
return JsonResponse({'error': 'Invalid request method'}, status=400)
领取专属 10元无门槛券
手把手带您无忧上云