简体   繁体   English

更新 Django 中的序列化程序数据

[英]Update serializer data in Django

I'm trying to add a dictionary to my serialized data but I'm getting an error dictionary update sequence element #0 has length 6; 2 is required我正在尝试将字典添加到我的序列化数据中,但出现错误dictionary update sequence element #0 has length 6; 2 is required dictionary update sequence element #0 has length 6; 2 is required

This is what I have tried:这是我尝试过的:

def get_data(self, request):

    created_by = User_Detail.objects.get(auth_token__isnull=False)
    newdict = {'created_by': created_by.id}
    details = ExSerializer(Tower.objects.all(), many=True).data
    newdict.update(details)
    return Response({"expenses": newdict})

I tried the above code but it's not working for me.我尝试了上面的代码,但它不适合我。

The root cause of this issue is you are trying to update a dictionary with a list.此问题的根本原因是您尝试使用列表更新字典。

The minimal code to simulate this issue:模拟此问题的最少代码:

d = {1: "one", 2: "three"}
d.update([(1,)])

will gives an error of将给出一个错误

Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
    d.update([(1,)])
ValueError: dictionary update sequence element #0 has length 1; 2 is required

For your case, you are updating newdict with a list coming from ExSerializer ( Tower.objects.all() with many=True ).对于您的情况,您正在使用来自newdict的列表( Tower.objects.all()many=True )更新ExSerializer

To solve this, you will need to adjust your code to extract only one record from Tower , or make a list of results that combine each user to one Tower record, depends on your exact use case.为了解决这个问题,您需要调整代码以仅从Tower中提取一条记录,或者制作一个将每个用户组合到一条Tower记录的结果列表,具体取决于您的确切用例。

-- EDIT -- - 编辑 -

If you want all records of Tower in one request, you will need to apply multiple serializers.如果您想要一个请求中的所有Tower记录,您将需要应用多个序列化程序。

The code will be similar to this (not tested):代码将与此类似(未测试):

def get_data(self, request):
    created_by = User_Detail.objects.get(auth_token__isnull=False)
    return Response({"expenses": UserDetailSerializer({"created_by": created_by}).data})


class UserDetailSerializer(serializers.ModelSerializer):
    created_by = serializers.IntegerField()
    details = serializers.SerializerMethodField()

    class Meta:
        model = User_Detail
        fields = ('created_by', 'details')

    def get_details(self, obj):
        return ExSerializer(Tower.objects.all(), many=True).data

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM