django 覆盖更新和to_representation方法在POST请求时抛出AttributeError

n8ghc7c1  于 2023-01-21  发布在  Go
关注(0)|答案(3)|浏览(115)

我尝试序列化Onetofield关系中两个模型的字段,因此我覆盖了序列化器中的update和to_representation方法。对于GET请求,一切正常,但是POST请求抛出了
属性错误位于/personalData/
"OrderedDict"对象没有属性"firstname"
错误。
我的模特:

class UserData(models.Model):
    user = models.OneToOneField(User)

    gender = models.CharField(max_length=20, blank=True)
    firstname = models.CharField(max_length=50, blank=True)
    lastname = models.CharField(max_length=50, blank=True)
    nationality = models.CharField(max_length=30, blank=True)

class Employee(models.Model):
    userData = models.OneToOneField(UserData)

    birthdate = models.CharField(max_length=30, blank=True)
    jobTitle = models.CharField(max_length=50, blank=True)

我的序列化程序类:

class EmployeePersonalDataSerializer(serializers.Serializer):
    firstname = serializers.CharField()
    lastname = serializers.CharField()
    birthdate = serializers.CharField()
    gender = serializers.CharField()
    jobTitle = serializers.CharField()
    nationality = serializers.CharField()

    def update(self, instance, validated_data):
        instance.firstname = validated_data.get('firstname', instance.firstname)
        instance.lastname = validated_data.get('lastname', instance.lastname)
        instance.gender = validated_data.get('gender', instance.gender)
        instance.nationality = validated_data.get('nationality', instance.nationality)
        instance.employee.jobTitle = validated_data.get('jobTitle', instance.employee.jobTitle)
        instance.employee.birthdate = validated_data.get('birthdate', instance.employee.birthdate)
        instance.employee.save()
        instance.save()
        return instance

    def to_representation(self, obj):
        return {
                    'firstname': obj.firstname,
                    'lastname': obj.lastname,
                    'birthdate': obj.employee.birthdate,
                    'gender': obj.gender,
                    'jobTitle': obj.employee.jobTitle,
                    'nationality': obj.nationality
                }
    • 编辑:**

完整的追溯:

Traceback:
File "/home/user/.local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  132.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/user/.local/lib/python2.7/site-packages/django/views/decorators/csrf.py" in wrapped_view
  58.         return view_func(*args, **kwargs)
File "/home/user/.local/lib/python2.7/site-packages/django/views/generic/base.py" in view
  71.             return self.dispatch(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/rest_framework/views.py" in dispatch
  466.             response = self.handle_exception(exc)
File "/usr/local/lib/python2.7/dist-packages/rest_framework/views.py" in dispatch
  463.             response = handler(request, *args, **kwargs)
File "/myproject/views.py" in post
  177.             serializer.update(instance=userData, validated_data=serializer.data)
File "/usr/local/lib/python2.7/dist-packages/rest_framework/serializers.py" in data
  487.         ret = super(Serializer, self).data
File "/usr/local/lib/python2.7/dist-packages/rest_framework/serializers.py" in data
  225.                 self._data = self.to_representation(self.validated_data)
File "/myproject/serializers.py" in to_representation
  226.                     'firstname': obj.firstname,

Exception Type: AttributeError at /personalData/
Exception Value: 'OrderedDict' object has no attribute 'firstname'
4ioopgfo

4ioopgfo1#

来自DRF文件
如果要实现读写关系字段,还必须实现.to_internal_value(self,data)方法。
因此,您希望实现一个读写(POST/GET)字段,因此需要在串行化器中实现.to_internal_value方法。

qcbq4gxm

qcbq4gxm2#

您需要使用嵌套的序列化程序。错误是说没有雇员的名字字段,实际上没有。您需要雇员和用户数据的序列化程序。

kyxcudwk

kyxcudwk3#

我最近遇到了同样的问题,我重写了序列化器的to_representationcreate方法。
在我的例子中,我忘记在我的视图集中添加serializer.save()。添加后问题得到了解决。
错误的原因是当我在视图集中调用序列化程序时,它将POST请求的主体作为OrderedDict传递给to_representation方法中的obj。

相关问题