我有一个角色模型。我正在尝试使用Django Rest Framework保存一个新的。
我的观点:
def create_character(request):
existing_character = Character.objects.filter(user=request.user)
if existing_character.count() > 0:
return HttpResponse(status=400)
request.GET = request.GET.copy()
request.GET["user"] = request.user.id
serializer = CharacterSerializer(data=request.GET)
if not serializer.is_valid():
return HttpResponse(status=401, content=serializer.errors)
serializer.save()
return Response(serializer.data)
我的模特:
class Character(models.Model):
user = models.OneToOneField(User)
name = models.CharField(max_length=50)
surname = models.CharField(max_length=50)
date_created = models.DateField()
age = models.SmallIntegerField()
health = models.SmallIntegerField()
happiness = models.SmallIntegerField()
depression = models.SmallIntegerField()
我的序列化器:
class CharacterSerializer(serializers.ModelSerializer):
health = serializers.IntegerField(required=False)
happiness = serializers.IntegerField(required=False)
depression = serializers.IntegerField(required=False)
date_created = serializers.DateField(required=False)
class Meta:
model = Character
fields = ('user', 'pk', 'name', 'surname', 'date_created', 'user', 'age', 'health', 'happiness', 'depression',
'date_created')
def create(self, validated_data):
validated_data["health"] = 100
validated_data["happiness"] = 100
validated_data["depression"] = 0
validated_data["date_created"] = date.today()
return User.objects.create(**validated_data)
当序列化程序调用{{1}}我的gettine异常时:
'姓'是此函数的无效关键字参数
答案 0 :(得分:2)
这是一个CharacterSerializer,但出于某种原因,你已经告诉它创建一个用户而不是一个角色。