使用序列化器的用户模型的django一对一字段

时间:2017-02-15 14:09:12

标签: django django-rest-framework serializer

用户模型和UserProfile模型与一对一字段连接。我想通过序列化程序发布数据,但程序出错......

这是型号代码..

class UserProfile(models.Model):
    GENDERS = (
        ('M', 'Male'),
        ('F', 'Female'),
        ('T', 'Transgender'),
    )
    user = models.OneToOneField(User)
    dob = models.DateField(null=True)   
    contactno = models.BigIntegerField(null=True)
    gender = models.CharField(max_length=1, choices=GENDERS,blank=True,    null=True)
    country = models.ForeignKey(Country, null=True)
    state = ChainedForeignKey(State,chained_field="country",    chained_model_field="country", null=True)
    city = ChainedForeignKey(City,chained_field="state",  chained_model_field="state", null=True)
    pin_code = models.IntegerField( null=True, blank=True, default = None)
    class Meta:
        verbose_name_plural = 'User Profile'
    def __unicode__(self):
        return str(self.user)

这是序列化代码......

class userProfileSerializer(serializers.ModelSerializer):

    class Meta:
        model = UserProfile
        fields = ("dob","contactno","country","state","city",'user')





class userSerializer(serializers.ModelSerializer):
    dob = userProfileSerializer()
    contactno = userProfileSerializer()
    country = countrySerializer()
    state = stateSerializer()
    city = citySerializer()
    class Meta:
        model = User
        fields =  ('username','email','password',"dob","contactno","country","state","city")


    def create(self, validated_data):
        dob_data = validated_data.pop('dob')
        contactno_data = validated_data.pop('contactno')
        country_data = validated_data.pop('country')
        state_data = validated_data.pop('state')
        city_data = validated_data.pop('city')


        user = User.objects.create(username=validated_data['username'],email=validated_data['email'],password=validated_data['password'])
        user.set_password(validated_data['password'])
        user.save()
                UserProfile.objects.create(user=user,dob=dob_data,contactno=contactno_data,country=country_data,state=state_data,city=city_data)
    return user
如果有人帮助我,那将是非常好的......

1 个答案:

答案 0 :(得分:1)

如果您只想保存UserProfile,则不需要UserProfile的特殊序列化程序。

以下是仅使用dob字段的最小示例,但相同的规则适用于其他字段。

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields =('username','email','password', 'dob')

    def create(self, validated_data):
        dob_data = validated_data.pop('dob')

        user = User.objects.create(
            username=validated_data.get('username'),
            email=validated_data.get('email'),
            password=validated_data.get('password')
        )
        user.set_password(validated_data.get('password'))
        user.save()

        UserProfile.objects.create(user=user, dob=dob_data)
        return user