如何正确序列化列表列表

时间:2019-04-23 09:55:33

标签: django serialization django-rest-framework serializer

我正在编写django API,我需要在其中返回列表列表。我尝试作为模型序列化器来执行此操作,但是当我开始建立列表响应列表时收到以下错误:

AttributeError: Got AttributeError when attempting to get a value for field `contract_number` on serializer `ContractsSignUpListSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `list` instance.

由于我需要从3个不同的表中提取属性,因此我开始构建响应,每次我使用它们各自的模型序列化程序时,都会给我其他模型之一的属性错误。

这些是我需要的属性,它们来自3个不同的表:

query = SignUpTable.objects.filter(empid_id__empid=int(input))

            for q in query:
                print q.empid.first_name,
                print q.empid.last_name,
                print q.signedup,
                print q.contract_number.contract_number,

我尝试返回有效的Query变量,但是当我需要另一个表的一个或两个属性,而不必在当前表上使用外键时,它仅向我提供当前表中的外键。

我还尝试了使用列表序列化程序返回列表列表,但是收到一个错误消息,提示未提供任何子项。

class ContractEmployeeResponseSerializer(serializers.ListSerializer):
    data = serializers.ListField(
        child = serializers.ListField(
            child = serializers.CharField(max_length=255)
        )
    )

我有3个表Employees,Contracts和SignUpTable,其中注册表具有其他两个表的主键empid和contract_number,并且用作事务的弱实体。

我看过许多序列化stackoverflow帖子,但似乎仍然缺少一些基本知识。

此序列化程序将显示我的外键信息,但不会为我提供访问我要从中检索字段的“雇员”或“合同”对象的权限。

class ContractsSignUpListSerializer(serializers.ModelSerializer):
    class Meta:
        model = SignUpTable
        fields = '__all__'

这是我要返回的视图:

class SignUpTableCreate(generics.ListCreateAPIView):
    # serializer_class = ContractEmployeeResponseSerializer
    serializer_class = ContractsSignUpListSerializer

    def get_queryset(self):
        input = self.request.parser_context['kwargs']['input']
        table = self.request.parser_context['kwargs']['table']
        print("input: ", input)
        print("table: ", table)

        if table == "Contracts":
            query = SignUpTable.objects.filter(contract_number_id__contract_number=str(input))
            for q in query:
                print q.empid.first_name,
                print q.empid.last_name,
                print q.signedup,
                print q.contract_number.contract_number,
                print "\n"
            ret = [[q.empid.first_name + ' ' + q.empid.last_name, q.contract_number.contract_number, str(q.signedup)] for q in query]

            return ret
            # return query

        elif table == "Employees":
            query = SignUpTable.objects.filter(empid_id__empid=int(input))

            for q in query:
                print q.empid.first_name,
                print q.empid.last_name,
                print q.signedup,
                print q.contract_number.contract_number,
                print "\n"
            ret = [[q.empid.first_name + ' ' + q.empid.last_name, q.contract_number.contract_number, str(q.signedup)] for q in query]

            return ret
            # return query

很明显,当我返回嵌套的列表列表时,使用模型序列化器会出错,但是即使使用上述列表序列化器,我也会收到以下完整显示的错误:

Internal Server Error: /ContractSignUp/api/SignUpTableCreate/Contracts/NX19-004
Traceback (most recent call last):
  File "C:\Users\dgutsch\Desktop\related-work-application\ENV\lib\site-packages\django\core\handlers\exception.py", line 41, in inner
    response = get_response(request)
  File "C:\Users\dgutsch\Desktop\related-work-application\ENV\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\dgutsch\Desktop\related-work-application\ENV\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\dgutsch\Desktop\related-work-application\ENV\lib\site-packages\django\views\decorators\csrf.py", line 58, in wrapped_view
    return view_func(*args, **kwargs)
  File "C:\Users\dgutsch\Desktop\related-work-application\ENV\lib\site-packages\django\views\generic\base.py", line 68, in view
    return self.dispatch(request, *args, **kwargs)
  File "C:\Users\dgutsch\Desktop\related-work-application\ENV\lib\site-packages\rest_framework\views.py", line 495, in dispatch
    response = self.handle_exception(exc)
  File "C:\Users\dgutsch\Desktop\related-work-application\ENV\lib\site-packages\rest_framework\views.py", line 455, in handle_exception
    self.raise_uncaught_exception(exc)
  File "C:\Users\dgutsch\Desktop\related-work-application\ENV\lib\site-packages\rest_framework\views.py", line 492, in dispatch
    response = handler(request, *args, **kwargs)
  File "C:\Users\dgutsch\Desktop\related-work-application\ENV\lib\site-packages\rest_framework\generics.py", line 241, in get
    return self.list(request, *args, **kwargs)
  File "C:\Users\dgutsch\Desktop\related-work-application\ENV\lib\site-packages\rest_framework\mixins.py", line 47, in list
    serializer = self.get_serializer(queryset, many=True)
  File "C:\Users\dgutsch\Desktop\related-work-application\ENV\lib\site-packages\rest_framework\generics.py", line 112, in get_serializer
    return serializer_class(*args, **kwargs)
  File "C:\Users\dgutsch\Desktop\related-work-application\ENV\lib\site-packages\rest_framework\serializers.py", line 124, in __new__
    return cls.many_init(*args, **kwargs)
  File "C:\Users\dgutsch\Desktop\related-work-application\ENV\lib\site-packages\rest_framework\serializers.py", line 145, in many_init
    child_serializer = cls(*args, **kwargs)
  File "C:\Users\dgutsch\Desktop\related-work-application\ENV\lib\site-packages\rest_framework\serializers.py", line 592, in __init__
    assert self.child is not None, '`child` is a required argument.'
AssertionError: `child` is a required argument.

0 个答案:

没有答案