我在Django中扩展了用户模型,它是Customer类型。我正在使用django rest framework(DRF)。因此,在浏览DRF中的文档时,我开始了解嵌套模型中的编写,因此我确实在序列化器中覆盖了创建和更新方法,创建工作正常但不是更新,因为它说:
HTTP 400 Bad Request
Allow: GET, PUT, PATCH, DELETE, OPTIONS
Content-Type: application/json
Vary: Accept
{
"user": {
"username": [
"A user with that username already exists."
]
}
}
这是我的客户模型:
from django.db import models
from django.contrib.auth.models import User
class Customer(models.Model):
user = models.OneToOneField(User, related_name="customer", on_delete=models.CASCADE)
date_of_birth = models.DateField(max_length=8)
def __unicode__(self):
return u'%s' % self.user.username
我的用户序列化程序:
from django.contrib.auth.models import User
from rest_framework import serializers
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('url', 'username', 'email', 'is_staff')
我的扩展客户模型序列化器:
from django.contrib.auth.models import User
from django.contrib.auth import get_user_model
from rest_framework import serializers
from customers.models import Customer
from api.serializers import UserSerializer
class CustomerSerializer(serializers.HyperlinkedModelSerializer):
user = UserSerializer()
class Meta:
model = Customer
fields = ('url', 'date_of_birth', 'user')
depth = 1
def create(self, validated_data):
print "coming inside create"
user_data = validated_data.pop("user")
user = User.objects.create(**user_data)
customer = Customer.objects.create(user=user, **validated_data)
return customer
def update(self, instance, validated_data):
print "coming inside update"
user_data = validated_data.pop("user")
username = user_data.pop('username')
user = get_user_model().objects.get_or_create(username=username)[0]
user.email = user_data.get('email', user.email)
user.save()
instance.user = user
instance.date_of_birth = validated_data.get('date_of_birth', instance.date_of_birth)
instance.save()
return instance
以下是视图集视图:
from rest_framework import viewsets
from customers.models import Customer
from customers.serializers import CustomerSerializer
class CustomerViewSet(viewsets.ModelViewSet):
serializer_class = CustomerSerializer
queryset = Customer.objects.all()
那么,这可能是错误的,即使新用户创建了新的客户资料但没有更新?
编辑1 好的,我在UserSerializer上做了这个:
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('url', 'username', 'email', 'is_staff')
extra_kwargs = {
'username': {'validators': []},
}
因此,更新适用于用户或客户字段的所有其他字段,但
并且在尝试创建新用户时,也会出现以下错误:
/ api / customers /
中的IntegrityError重复键值违反唯一约束“auth_user_username_key” 详细信息:密钥(用户名)=(customer1)已存在。
答案 0 :(得分:4)
您应该删除嵌套序列化程序的唯一验证器:
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('url', 'username', 'email', 'is_staff')
extra_kwargs = {
'username': {'validators': []},
}
您可能需要先打印序列化程序,以确保在该字段上没有其他验证程序。如果你有一些,你必须将它们包括在列表中。