非模型字段序列化的AttributeError

时间:2018-07-01 05:02:25

标签: django django-rest-framework

我有一个模特:

class Company(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, null=True)
    name = models.CharField(max_length=30, blank=True)
    balance = models.DecimalField(max_digits=10, decimal_places=2, default=0)
    phone_number = PhoneNumberField(null=True, blank=True)
    active = models.BooleanField(default=False)

我需要序列化用户和模型的创建。想法是在注册时询问用户公司名称,所以我有:

class CreateUserSerializer(serializers.ModelSerializer):
    company_name = serializers.CharField(required=True)

    class Meta:
        model = User
        fields = ('id', 'company_name', 'username', 'email', 'password')
        extra_kwargs = {'password': {'write_only': True}}

    def create(self, validated_data):
        username = validated_data['username']
        email = validated_data['email']
        password = validated_data['password']
        company_name = validated_data['company_name']
        user = User.objects.create(username=username, email=email, password=password)
        Company.objects.create(user=user, name=company_name)
        return user

我收到错误消息:

  

尝试获取字段值时出现AttributeError   company_name在串行器CreateUserSerializer上。序列化器   字段名称可能不正确,并且与任何属性或键都不匹配   User实例。原始异常文本为:“用户”对象没有   属性“ company_name”。

创建了任何对象公司和用户,因为我可以在管理面板中看到它。 我在做什么错,我该如何解决?

1 个答案:

答案 0 :(得分:1)

在这种情况下,您可以使用source字段的参数:

The following NEW packages will be installed:
  php7.2-ldap
0 upgraded, 1 newly installed, 0 to remove and 28 not upgraded.
Need to get 23.1 kB of archives.
After this operation, 101 kB of additional disk space will be used.
Err:1 http://ppa.launchpad.net/ondrej/php/ubuntu xenial/main amd64 php7.2-ldap amd64 7.2.4-1+ubuntu16.04.1+deb.sury.org+1
  404  Not Found
E: Failed to fetch http://ppa.launchpad.net/ondrej/php/ubuntu/pool/main/p/php7.2/php7.2-ldap_7.2.4-1+ubuntu16.04.1+deb.sury.org+1_amd64.deb 404  Not Found

E: Unable to fetch some archives, maybe run apt-get update or try with --fix-missing?
ERROR: Service 'workspace' failed to build: The command '/bin/sh -c if [ ${INSTALL_LDAP} = true ]; then     apt-get install -y libldap2-dev &&     apt-get install -y php${PHP_VERSION}-ldap ;fi' returned a non-zero code: 100