如何 POST 到具有 GenericForeignKey 的 modelViewSet?

How to POST to a modelViewSet that has a GenericForeignKey?

我有一个使用 django 内容类型框架的模型

class Foo(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    content_type = models.ForeignKey(ContentType, on_delete=models.PROTECT)
    object_id = models.UUIDField()
    contentObject = GenericForeignKey()

然后我使用 modelViewSet 和序列化程序

class FooViewSet(viewsets.ModelViewSet):
    serializer_class = FooSerializer
    queryset = Foo.objects.all()

class FooSerializer(serializers.ModelSerializer):
    class Meta:
        model = Foo
        fields = ('__all__')

如何使用 POST 为 viewSet 创建数据? 我任意尝试 POST 从另一个模型到 content_typeobject_idcontent_object 的对象 ID 然后我得到错误 "Incorrect type. Expected pk value, received str."

我已经查看了 http://www.django-rest-framework.org/api-guide/relations/#generic-relationships 或堆栈溢出,但找不到任何关于如何 POST 数据的信息,可能是我的搜索不够彻底,抱歉。感谢您查看我的问题

更新

我试图重写序列化程序中的创建方法: 我尝试从 get_for_model 方法获取 ContentType 对象,但它 return AttributeError: 'AnotherModelX' object has no attribute 'replace'

def create(self, validated_data):
        content_type =  validated_data.get("object_id")
        taggedObject = AnotherObject1.objects.get(id=content_type) if AnotherObject1.objects.filter(id=content_type).count() > 0 else None
        taggedObject = AnotherObject2.objects.get(id=content_type) if AnotherObject2.objects.filter(id=content_type).count() > 0 and taggedObject == None else None

        if taggedObject is not None:
            contentType = ContentType.objects.get_for_model(taggedObject)
            if contentType is not None:
                validated_data["content_type"] = contentType
                validated_data["object_id"] = taggedObject
        return super(FooSerializer, self).create(validated_data)

class Meta:
    model = Foo
    fields = ('__all__')
    extra_kwargs = {
        'content_type': {'required': False},

原来我的上次更新已经接近解决方案了, 它应该在 validated_data["object_id] 中分配一个 id 然后它工作。这是 POST json 到 Foo 的数据:

{
  "object_id": <<another_model_uuid>>
}

确保获取所有可能的模型,以便 taggedObject 包含模型的实例。

现在已经解决了,谢谢!

下面是序列化程序

中正确的 create 方法
def create(self, validated_data):
        content_type =  validated_data.get("object_id")
        taggedObject = AnotherObject1.objects.get(id=content_type) if AnotherObject1.objects.filter(id=content_type).count() > 0 else None
        taggedObject = AnotherObject2.objects.get(id=content_type) if AnotherObject2.objects.filter(id=content_type).count() > 0 and taggedObject == None else None

        if taggedObject is not None:
            contentType = ContentType.objects.get_for_model(taggedObject)
            if contentType is not None:
                validated_data["content_type"] = contentType
                validated_data["object_id"] = taggedObject.id
        return super(FooSerializer, self).create(validated_data)