2017-02-15 25 views
0

用戶模型和用戶配置模型與一個對一個字段連接。我希望通過發佈數據序列化,但程序給出錯誤...Django的一對一個領域與用戶模型使用串行

這是模型代碼..

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 

這將是非常巨大的,如果有人幫我....

+0

顯示錯誤會很有用。 –

回答

0

如果你只是想要保存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 
+0

當我使用POST方法時,它會給出錯誤... {「user」:[「此字段是必需的。」]} –

+0

您是否正在複製我的示例逐字?因爲在我的例子中'user'正在創建'UserProfile'實例時被設置,所以它不會給出這個錯誤。請按原樣使用我的示例並嘗試從那裏開始工作。 – mislavcimpersak

+0

感謝您的回覆....其工作 –

相關問題