Django休息框架一对一关系更新序列化器

时间:2016-09-21 07:45:50

标签: python django django-rest-framework

我是Django Rest Frame工作的初学者。我有很长一段时间的问题,我试图通过许多论坛找到解决方案但不幸的是我没有成功。希望你帮助我

models.py

from __future__ import unicode_literals
from django.contrib.auth.models import User

from django.db import models

class Account(models.Model):
    my_user=models.OneToOneField(User,on_delete=models.CASCADE)
    statut=models.CharField(max_length=80)
    date=models.DateField(auto_now=True,auto_now_add=False)

    def __unicode__(self):

      return self.my_user.first_name

现在我想更新Account serilizer。 序列化程序.py

class AccountUpdateSerializer(serializers.ModelSerializer):


    username=serializers.CharField(source ='my_user.username')

    class Meta:

        model= Account
        fields=['id','username','statut','date']
        def update(self, instance, validated_data):
            print(instance)
            instance.statut = validated_data.get('statut', instance.statut)
            instance.my_user.username=validated_data['username']
            return instance
追回:     环境:

Request Method: PUT
Request URL: http://127.0.0.1:9000/api/account/edit/1/

Django Version: 1.9
Python Version: 2.7.6
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'rest_framework',
 'project',
 'sponsors',
 'contacts',
 'medias',
 'conferencier',
 'competition',
 'poste',
 'account']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']



Traceback:

File "/home/asus/Documents/Gsource/gsource/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  149.                     response = self.process_exception_by_middleware(e, request)

File "/home/asus/Documents/Gsource/gsource/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  147.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/home/asus/Documents/Gsource/gsource/local/lib/python2.7/site-packages/django/views/decorators/csrf.py" in wrapped_view
  58.         return view_func(*args, **kwargs)

File "/home/asus/Documents/Gsource/gsource/local/lib/python2.7/site-packages/django/views/generic/base.py" in view
  68.             return self.dispatch(request, *args, **kwargs)

File "/home/asus/Documents/Gsource/gsource/local/lib/python2.7/site-packages/rest_framework/views.py" in dispatch
  474.             response = self.handle_exception(exc)

File "/home/asus/Documents/Gsource/gsource/local/lib/python2.7/site-packages/rest_framework/views.py" in handle_exception
  434.             self.raise_uncaught_exception(exc)

File "/home/asus/Documents/Gsource/gsource/local/lib/python2.7/site-packages/rest_framework/views.py" in dispatch
  471.             response = handler(request, *args, **kwargs)

File "/home/asus/Documents/Gsource/gsource/local/lib/python2.7/site-packages/rest_framework/generics.py" in put
  256.         return self.update(request, *args, **kwargs)

File "/home/asus/Documents/Gsource/gsource/local/lib/python2.7/site-packages/rest_framework/mixins.py" in update
  70.         self.perform_update(serializer)

File "/home/asus/Documents/Gsource/gsource/local/lib/python2.7/site-packages/rest_framework/mixins.py" in perform_update
  74.         serializer.save()

File "/home/asus/Documents/Gsource/gsource/local/lib/python2.7/site-packages/rest_framework/serializers.py" in save
  187.             self.instance = self.update(self.instance, validated_data)

File "/home/asus/Documents/Gsource/gsource/local/lib/python2.7/site-packages/rest_framework/serializers.py" in update
  907.             setattr(instance, attr, value)

File "/home/asus/Documents/Gsource/gsource/local/lib/python2.7/site-packages/django/db/models/fields/related_descriptors.py" in __set__
  207.                     self.field.remote_field.model._meta.object_name,

Exception Type: ValueError at /api/account/edit/1/
Exception Value: Cannot assign "{u'username': u'kais'}": "Account.my_user" must be a "User" instance.

1 个答案:

答案 0 :(得分:2)

您的update方法未被调用,因为它是序列化程序的元类(AccountUpdateSerializer.Meta)的方法,而不是序列化程序类AccountUpdateSerializer本身。

以下是它的外观:

class AccountUpdateSerializer(serializers.ModelSerializer):

    username=serializers.CharField(source ='my_user.username')

    class Meta:

        model= Account
        fields=['id','username','statut','date']

    def update(self, instance, validated_data):
        print(instance)
        instance.statut = validated_data.get('statut', instance.statut)
        instance.my_user.username = validated_data['username']
        return instance

(或者你刚才错误地发布了你的代码?)