在Django REST中扩展用户模型字段后无法POST

时间:2015-04-17 14:59:06

标签: django api rest django-rest-framework

我能够扩展用户模型字段,我可以看到带有这些字段和输入的API浏览器,但是当我尝试POST新用户时,我收到了这个错误:

'signup' is an invalid keyword argument for this function

或者如果我更改 serializers.py

User.objects.create(**validated_data) 

SignUp.objects.create(**validated_data)

我得到了

'username' is an invalid keyword argument for this function

serializers.py

from rest_framework import serializers
from django.contrib.auth.models import User


class UserSerializer(serializers.ModelSerializer):
    city = serializers.CharField(source='signup.city')

    class Meta:
        model = User
        fields = ('username', 'first_name', 'last_name', 'city')

    def create(self, validated_data):
        return User.objects.create(**validated_data)

models.py

from django.contrib.gis.db import models
from django.contrib.auth.models import User

class SignUp(models.Model):
    user=models.OneToOneField(User, primary_key=True)
    city = models.CharField(max_length=50, blank=True)

    def __unicode__(self):
        return self.first_name

1 个答案:

答案 0 :(得分:0)

您需要通过模型中的related_name field执行此操作,然后才能在序列化程序中引用它。

class SignUp(models.Model):
    user=models.OneToOneField(User, primary_key=True, related_name='signup') # <---

我认为您不能将嵌套字段拼合到父模型的序列化程序中。

您可以执行嵌套字段:

class UserSerializer(serializers.ModelSerializer):
    city = serializers.CharField(source='signup')

如果您通过JSON路径访问它,您将获得一个对象:

{
    url: "localhost:8000/users/1",
    username: "foo",
    email: "foo@example.com",
    signup: {
        city: "Seattle"
    }
 }