2017-05-29 56 views
0

更新OneToOneField通過串行我有2個型號的國家,用戶,用戶與國家的關係我們如何能夠在DRF

class Country(models.Model): 
    country_id = models.AutoField(primary_key = True) 
    country_name = models.CharField(max_length = 128) 

    class Meta: 
     db_table = 'country' 

class User(models.Model): 
    user_id = models.AutoField(primary_key = True) 
    country = models.OneToOneField(Country, related_name='country_model') 
    name = models.CharField(max_length = 12) 

    class Meta: 
     db_table = 'User' 

我寫下串行用戶

class UserSerializer(serializers.ModelSerializer): 
    country_detail = CountrySerializer(source = 'country',required=False) 
    class Meta: 
     model = User 
     fields = ['country','name','country_detail'] 

現在,鑑於我已經寫下了這個

obj = User.objects.get(pk = 996) 
#data pass this 
{"name": "abc" , "country":"545"} 
UserSerializer(obj, data) # it show me error type object 'User' has no attribute country 'DoesNotExit' 

如果我刪除OneToOneField關係,那麼我將保存數據沒有呃ROR

什麼錯在這個

回答

0

一旦您指定在UserSerializer全國領域的另一個名字(country_detail),這是你應該創建用戶的過程中傳遞給UserSerializer,像這樣的領域:

obj = User.objects.get(pk = 996) 
#data passed: 
{"name": "abc" , "country_detail":"545"} 
UserSerializer(obj, data) 
相關問題