You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Django REST Framework中序列化非模型字典遇阻求助

How to Serialize a Custom Integer-Keyed Dictionary in Django REST Framework

Got it, let's tackle this serialization issue. Your data is a custom dictionary with integer keys (like 101) mapping to quiz details—since this isn't tied to a Django model, we'll use DRF's core Serializer classes instead of ModelSerializer to handle this structure cleanly.

Step 1: Define a Serializer for Individual Quiz Details

First, create a serializer to handle the inner structure of each quiz entry (the subject and topics fields):

from rest_framework import serializers

class QuizDetailSerializer(serializers.Serializer):
    subject = serializers.CharField()
    topics = serializers.ListField(child=serializers.CharField())

This serializer validates and formats the nested dictionary data for each quiz, ensuring the fields match the expected types.

Step 2: Serialize the Outer Integer-Keyed Dictionary

Since your top-level data is a dictionary with dynamic integer keys, use DRF's DictField to wrap the QuizDetailSerializer—this tells DRF to apply the quiz detail serializer to every value in the dictionary.

Option 1: Direct Serialization in a View

If you just need to serialize the raw dictionary directly in a view:

from rest_framework.views import APIView
from rest_framework.response import Response

class QuizDataView(APIView):
    def get(self, request):
        # Your processed quiz data dictionary
        quiz_data = {
            101: {
                'subject': 'General-Intelligence',
                'topics': ['Coding Decoding', 'Dice & Boxes', 'Statement & Conclusion', ...]
            },
            # Add other quiz entries here
        }
        
        # Use DictField with the inner serializer to process the whole dictionary
        serializer = serializers.DictField(child=QuizDetailSerializer())
        serialized_data = serializer.to_representation(quiz_data)
        
        return Response(serialized_data)

Option 2: Wrap in a Top-Level Serializer (for structured responses)

If you want to wrap the dictionary in a named key (like quizzes) for a more API-friendly, organized response:

class QuizCollectionSerializer(serializers.Serializer):
    quizzes = serializers.DictField(child=QuizDetailSerializer())

# Then in your view:
class QuizDataView(APIView):
    def get(self, request):
        quiz_data = { ... } # Your processed quiz data
        serializer = QuizCollectionSerializer(data={'quizzes': quiz_data})
        serializer.is_valid(raise_exception=True)
        return Response(serializer.data)

Important Note

JSON only supports string keys, so your integer keys (like 101) will be automatically converted to strings in the serialized response. This is standard behavior—your frontend can easily parse these back to integers if needed.

Quick Local Test

You can verify the serialization works without a view too:

quiz_data = {101: {'subject': 'General-Intelligence', 'topics': ['Coding Decoding']}}
serializer = serializers.DictField(child=QuizDetailSerializer())
print(serializer.to_representation(quiz_data))
# Output: {'101': {'subject': 'General-Intelligence', 'topics': ['Coding Decoding']}}

内容的提问来源于stack exchange,提问作者Prashant Pandey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:57:08