嵌套字段序列化程序 - 数据缺失

时间:2015-01-09 10:08:32

标签: python django django-rest-framework

  

Related to this Topic


您好, 我无法按照附件中的回答,因为序列化后缺少 ID

  • Model.py

class Owner(models.Model):
    name = models.CharField(db_index=True, max_length=200)

class Car(models.Model):
    name = models.CharField(db_index=True, max_length=200)
    LCVS  = models.ForeignKey(Owner)
  • View.py

class OwnerViewSet(viewsets.ModelViewSet):
    queryset = Owner.objects.all()
    serializer_class = OwnerSerializer

class CarViewSet(viewsets.ModelViewSet):
    serializer_class = CarSerializer
    queryset = Car.objects.all()
  • Serializer.py

class OwnerSerializer(serializers.ModelSerializer):
    class Meta:
        model =  Owner
        fields = ('id', 'name')

class CarSerializer(serializers.ModelSerializer):
    owner = OwnerSerializer() 

    class Meta:
        model =  Car
        fields = ('id', 'name', 'owner')

    def create(self, validated_data):
        tmp_owner = Owner.objects.get(id=validated_data["car"]["id"])
        car = Car.objects.create(name=self.data['name'],owner=tmp_owner)
        return car

现在我发送以下请求:

Request URL:http://localhost:9000/api/v1/cars
Request Method:POST
Request Paylod :
{
    "name": "Car_test", 
    "ower": {
        "id":1,
        "name": "Owner_test"
    }
}

但是,此处validated_data不包含所有者ID!

追溯|本地变量

 validated_data {u'Owner': OrderedDict([(u'name', u'Owner_test')]), u'name': u'Car_test'} 

@Kevin Brown:
工作!谢谢 我会验证你的答案,但我遇到了一个新问题...

现在,当我尝试设置新的所有者时,会出现错误:

{
    "id": [
        "This field is required."
    ]
}

我必须创建一个新的序列化程序?

1 个答案:

答案 0 :(得分:14)

当Django REST Framework在后台创建字段时,模型上的任何AutoField(自动生成的id键都是)默认设置为只读。您可以通过

确认
repr(CarSerializer())

并查看使用read_only=True设置生成的字段。您可以覆盖此with the extra_kwargs Meta option,以便覆盖它并设置read_only=False

class OwnerSerializer(serializers.ModelSerializer):

    class Meta:
        model =  Owner
        fields = ('id', 'name')
        extra_kwargs = {
            "id": {
                "read_only": False,
                "required": False,
            },
        }

这将在您需要时包含id中的validated_data字段。