Skip to main content
 首页 » 编程设计

python之Django 序列化程序 : Getting an ordered dictionary in embeded serializer

2024年12月31日22EasonJim

我是一个序列化程序在另一个序列化程序中以显示来自一个模型的信息,并在同一响应中显示来自另一个模型的选定字段。

看起来像这样:

class SimpleRouteClientConstraintSerializer(serializers.ModelSerializer): 
 
     name = serializers.SerializerMethodField() 
 
    def get_name(self, obj): 
        default_constraint = RouteDefaultConstraint.objects.get(pk=obj.route_default_constraint_id) 
        return default_constraint.name 
 
    class Meta: 
        model = RouteClientConstraint 
        fields = ('name', 'value') 
 
class RouteSerializer(serializers.ModelSerializer): 
    ... 
    # Calling first serializer here 
    routeClientConstraints = SimpleRouteClientConstraintSerializer(many=True, required=False) 
    ... 
 
    class Meta: 
        model = Route 
        fields = (..., 'routeClientConstraints', ...) 
        depth = 1 

当运行 RouteSerilalizer 时,我想要一个响应:

'routeClientConstraints': [{ 
    'name': 'my name' 
    'value': 'confused' 
}, 
... 
] 

如果我像上面的代码一样使用序列化器,我会得到

'routeClientConstraints': [ 
    OrderedDict([ 
        ('name', 'Minimum life boats'), 
        ('value', '6') 
    ]) 
] 

我尝试将序列化程序更改为:routeClientConstraints = SimpleRouteClientConstraintSerializer(many=True, required=False).data,我希望它会给我 json 格式,但我得到了这个:

'routeClientConstraints': [ 
    OrderedDict([ 
        ('id', 1), 
        ('value', '6'),  
        ('created_at', '2018-11-10T14:17:39.263848Z'),  
        ('updated_at', '2018-11-10T14:17:39.263861Z'),  
        ('route_default_constraint', 1),  
        ('route', 1)]) 
] 

我如何返回字典列表?

请您参考如下方法:

尽管您在调试输出中看到了 OrderedDict([...]),但 OrderedDict 实际上是一个 dict,所以当转换为 JSON 时,它将产生您期望的结果。