[升级到Django 2后的TypeError和AssertionError

问题描述 投票:0回答:1

我的任务是将Django REST框架项目从Django 1.8升级到Django2.x。我已经将整个代码从python 2.7移植到python 3.7,从Django 1.8移植到2.0.13。我正在使用虚拟环境。

我让它在python 3.7和Django 2.0.13以及RESTframework 3.11上运行,尽管在尝试创建新对象时遇到了问题。

这是我的问题的追溯:

Traceback (most recent call last):
  File "C:\Users\user1\Envs\projpy3\lib\site-packages\django\core\handlers\exception.py", line 35, in inner
    response = get_response(request)
  File "C:\Users\user1\Envs\projpy3\lib\site-packages\django\core\handlers\base.py", line 128, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\user1\Envs\projpy3\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\user1\Envs\projpy3\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
    return view_func(*args, **kwargs)
  File "C:\Users\user1\projects\proj_py3\rest_framework\viewsets.py", line 114, in view
    return self.dispatch(request, *args, **kwargs)
  File "C:\Users\user1\projects\proj_py3\rest_framework\views.py", line 505, in dispatch
    response = self.handle_exception(exc)
  File "C:\Users\user1\projects\proj_py3\rest_framework\views.py", line 465, in handle_exception
    self.raise_uncaught_exception(exc)
  File "C:\Users\user1\projects\proj_py3\rest_framework\views.py", line 476, in raise_uncaught_exception
    raise exc
  File "C:\Users\user1\projects\proj_py3\rest_framework\views.py", line 502, in dispatch
    response = handler(request, *args, **kwargs)
  File "C:\Users\user1\projects\proj_py3\rest_framework\mixins.py", line 18, in create
    serializer.is_valid(raise_exception=True)
  File "C:\Users\user1\projects\proj_py3\rest_framework\serializers.py", line 219, in is_valid
    self._validated_data = self.run_validation(self.initial_data)
  File "C:\Users\user1\projects\proj_py3\rest_framework\serializers.py", line 418, in run_validation
    value = self.to_internal_value(data)
  File "C:\Users\user1\projects\proj_py3\rest_framework\serializers.py", line 471, in to_internal_value
    for field in fields:
  File "C:\Users\user1\projects\proj_py3\rest_framework\serializers.py", line 354, in _writable_fields
    for field in self.fields.values():
  File "C:\Users\user1\Envs\projpy3\lib\site-packages\django\utils\functional.py", line 36, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "C:\Users\user1\projects\proj_py3\rest_framework\serializers.py", line 348, in fields
    for key, value in self.get_fields().items():
  File "C:\Users\user1\projects\proj_py3\rest_framework\serializers.py", line 1027, in get_fields
    field_names = self.get_field_names(declared_fields, info)
  File "C:\Users\user1\projects\proj_py3\rest_framework\serializers.py", line 1128, in get_field_names
    serializer_class=self.__class__.__name__
AssertionError: The field 'participantIDs' was declared on serializer OrderSerializer, but has not been included in the 'fields' option.

我不明白为什么该异常仅出现在新版本的代码中,因为除了版本更新外,我没有更改modelsserializersviews

这是有问题的serializer的样子:

class OrderSerializer(serializers.ModelSerializer):
    created_by = ShortPersonSerializer(read_only=True, required=False)
    modified_by = ShortPersonSerializer(read_only=True, required=False)
    customer = OrderPersonSerializer(required=False, allow_null=True, partial=True)
    ...
    ...
    participantIDs = serializers.SlugRelatedField(many=True, required=False, allow_null=True, slug_field='id', source='participants', queryset=Person.objects.all())
    ...
    ...

    class Meta:
        model = Order
        fields = ('id', 'title','customer', 
                    'customer_copy_id', 'customer_copy_salutation', 'customer_copy_first_name', 'customer_copy_last_name', 'created_at', 'created_by', 'modified_at', 'modified_by')

     def create(self, validated_data):
        customer_data = validated_data.pop('customer', None)
        participants_data = validated_data.pop('participants', None)

        if customer_data and customer_data is not None:
            validated_data['customer'] = Person(pk=customer_data['id'])

        order = Order.objects.create(**validated_data)

        if participants_data and participants_data is not None:
            setattr(order, 'participants', participants_data)      # line 1
            order.save()                                           # line 2
...           

其他信息:在检测到此错误之前,我得到了另一个错误,并具有以下回溯:

Traceback (most recent call last):
  ...
  ...
  File "C:\Users\user1\projects\proj_py3\rest_framework\serializers.py", line 204, in save
    self.instance = self.create(validated_data)
  File "C:\Users\user1\projects\proj_py3\orders\serializers.py", line 90, in create
    setattr(order, 'participants', participants_data)
  File "C:\Users\user1\Envs\projpy3\lib\site-packages\django\db\models\fields\related_descriptors.py", line 509, in __set__
    % self._get_set_deprecation_msg_params(),
TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use participants.set() instead.

所以我像这样更改了serializer

...
...
        if participants_data and participants_data is not None:
            #setattr(order, 'participants', participants_data)      # line 1
            order.save()                                           # line 2
            order.participants.set(participants_data)
...

自从完成此操作后,我得到了AssertionError而不是TypeError,而且我不知道该如何解决该问题。当然,我将代码改回去,但是我还删除了项目目录中的所有编译文件,删除了虚拟环境并创建了一个新的环境,在Windows上运行了磁盘清理,甚至卸载了Python37进行安装。再次。始终在两者之间重新引导。全部无济于事。


更新:

我将项目的update文件中的createserializers.py方法与我正在使用的rest_framework版本中的方法进行了比较:rest_framework/serializers.py on GitHub

我根据Django REST框架的较新版本对其进行了更改(该代码是为较旧版本开发的。)>

[我还检查了项目中其他应用程序的所有serializers,但我发现,除相关应用程序orders之外,所有其他应用程序在其attributeparticipantsID中都具有Serializer Meta类,以防它应该通过对方的Serializer访问对方的应用程序。

在那种情况下,就像注释中建议的那样:AssertionError一直在那里。

除了将attribute添加到fields之外,无需执行其他任何操作。>>

我的任务是将Django REST框架项目从Django 1.8升级到Django2.x。我已经将整个代码从python 2.7移植到python 3.7,从Django 1.8移植到2.0.13。我正在使用虚拟...

participantIDs

添加到fieldsOrderSerializer类的Meta
属性中>
class OrderSerializer(serializers.ModelSerializer):
    # other code snippets
    class Meta:
        model = Order
        fields = (other-fields, 'participantIDs')
    # other code snippets
django python-3.x django-models django-rest-framework django-serializer
1个回答
1
投票

participantIDs

© www.soinside.com 2019 - 2024. All rights reserved.