我们如何在DRF中通过串行器更新OneToOneField

时间:2017-05-29 11:44:43

标签: django-rest-framework

我有2个模型国家/地区和用户,用户与国家/地区有关系

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关系,那么我将保存数据而不会出现错误

这个错误

1 个答案:

答案 0 :(得分:0)

在UserSerializer中为country字段指定另一个名称(country_detail)后,这是您在创建用户期间应传递给UserSerializer的字段,如下所示:

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