在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

