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

Django中如何将Serializer数据转为dict及Query字符串转指定格式dict

Got it, let's break down your two questions one by one—both are super common when working with Django and DRF, so I’ve got you covered.

1. Converting Django Serializer Data to a Dictionary

Django REST Framework (DRF) serializers give you a couple straightforward ways to get plain Python dictionaries from their output:

  • Using serializer.data
    When you serialize a model instance or queryset, serializer.data returns either a ReturnDict (for single instances) or ReturnList (for multiple instances). These are subclasses of Python’s native dict and list, so they work like regular collections out of the box. If you need a strict native dict, just wrap it with dict():

    from rest_framework import serializers
    from myapp.models import MyModel
    
    class MyModelSerializer(serializers.ModelSerializer):
        class Meta:
            model = MyModel
            fields = '__all__'
    
    # For a single instance
    instance = MyModel.objects.first()
    serializer = MyModelSerializer(instance)
    data_dict = dict(serializer.data)  # Converts to a native dict
    
    # For a queryset (multiple instances)
    queryset = MyModel.objects.all()
    serializer = MyModelSerializer(queryset, many=True)
    data_list = list(serializer.data)  # Each item is a native dict
    
  • Using serializer.validated_data
    If you’re working with incoming data (like in a view where you validate user input), after calling serializer.is_valid(), validated_data holds an OrderedDict of all cleaned, validated values. Convert it to a regular dict the same way:

    serializer = MyModelSerializer(data=request.data)
    if serializer.is_valid():
        validated_dict = dict(serializer.validated_data)
        # Use this dict for creating/updating models or other logic
        instance = serializer.save()
    
2. Converting String-formatted Query Data to a Target Dictionary

First, let’s cover the two most common formats for this string data:

Case 1: URL Query Parameter String (e.g., "key1=val1&key2=val2&key2=val3")

Django’s built-in QueryDict is made for this exact scenario—it handles URL query strings, including duplicate keys:

from django.http import QueryDict

# Example query string
query_str = "username=john_doe&email=john@example.com&tags=python&tags=django"

# Parse into a QueryDict
query_dict = QueryDict(query_str)

# Convert to a simple dict (duplicate keys take the last value)
simple_dict = query_dict.dict()
# Output: {'username': 'john_doe', 'email': 'john@example.com', 'tags': 'django'}

# If you need to keep all values for duplicate keys (as lists)
multi_valued_dict = {key: query_dict.getlist(key) for key in query_dict}
# Output: {'username': ['john_doe'], 'email': ['john@example.com'], 'tags': ['python', 'django']}

Case 2: JSON-formatted String

If your query data is a JSON string, use Python’s built-in json module to parse it directly into a dict:

import json

# Example JSON string
json_query_str = '{"username": "john_doe", "email": "john@example.com", "tags": ["python", "django"]}'

# Parse into a dict
target_dict = json.loads(json_query_str)
# Output: {'username': 'john_doe', 'email': 'john@example.com', 'tags': ['python', 'django']}

内容的提问来源于stack exchange,提问作者Abhishek Kumar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 03:33:23