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

Nested field serializer - Data missing

Related to this Topic


你好, 我无法按照所附主题的答案进行操作,因为序列化后缺少 ID

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)

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

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

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'} 

@凯文·布朗:
工作!谢谢 我会验证你的答案,但我遇到了一个新问题...

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

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

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

当 Django REST Framework 在后台创建字段时,模型上的任何 AutoFields(这是自动生成的 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 中。