0

我已经按照官方指南在 Django DRF 中实现了通用关系,它运行良好,除了我似乎无法从我的 API 响应中获取字段 content_object 的事实。

基本上,我有一个名为 Document 的模型,它可以与一个名为 Folder 的模型或一个名为 Collection 的模型相关。

class Document(models.Model):

    limit = models.Q(app_label='folders', model='folder') | models.Q(
        app_label='collections', model='collection')

    title = models.CharField(max_length=500)
    # Field necessari per la Generic Relation
    content_type = models.ForeignKey(
        ContentType, on_delete=models.CASCADE, null=True, blank=True, limit_choices_to=limit)
    object_id = models.PositiveIntegerField(null=True, blank=True)
    content_object = GenericForeignKey(
        'content_type', 'object_id')
    category = models.CharField(max_length=30, blank=True, null=True)

    def __str__(self):
        return self.title


class Folder(models.Model):
    ...
    documents = GenericRelation(Document)

    def __str__(self):
        return self.title

class Collection(models.Model):
    ...
    documents = GenericRelation(Document)

    def __str__(self):
        return self.title


这是我的序列化程序:

class ContentObjectRelatedField(serializers.RelatedField):

    def to_representation(self, value):

        if isinstance(value, Folder):
            serializer = FolderSerializer(value)
        elif isinstance(value, Collection):
            serializer = CollectionSerializer(value)
        else:
            raise Exception('Unexpected type of object')

        return serializer.data


class DocumentSerializer(serializers.ModelSerializer):

    class Meta:
        model = Document
        fields = ('id', 'title', 'content_type',
                  'object_id', 'category')


class FolderSerializer(serializers.ModelSerializer):
    documents = DocumentSerializer(many=True, read_only=True)

    class Meta:
        model = Folder
        fields = ("id", "title", "description",
                  "documents")
        depth = 1

(Collection serializer is essentially the same ad the Folder serializer, with its own fields).

我期望能够在检索时访问字段 content_object 的内容 - 使用对 API 端点的 GET 请求 - 文档。相反,该字段不可用。如果我尝试将其添加到其序列化程序中列出的字段中,则会引发错误。

我如何访问该内容,以便我知道对于每个文档,确切属于哪个文件夹或哪个集合?

非常感谢。

4

1 回答 1

0

尝试这个:

class ContentObjectRelatedField(serializers.RelatedField):
    def to_representation(self, value):
        if isinstance(value, Folder):
            serializer = FolderForDocumentSerializer(value)
        elif isinstance(value, Collection):
            serializer = CollectionForDocumentSerializer(value) # Defines CollectionForDocumentSerializer in the same manner of FolderForDocumentSerializer
        else:
            raise Exception('Unexpected type of object')

        return serializer.data


class FolderForDocumentSerializer(serializers.ModelSerializer):
    class Meta:
        model = Folder
        fields = ("id", "title", "description")
        depth = 1


class DocumentSerializer(serializers.ModelSerializer):
    content_object = ContentObjectRelatedField(read_only=True)
   
    class Meta:
        model = Document
        fields = ('id', 'title', 'content_object', 'category')

# Note that you can use DocumentSerializer and CollectionSerializer, but not in ContentObjectRelatedField.to_representation

您的前端可以扣除检查返回字段的 content_object 的类型

于 2021-08-27T14:52:03.153 回答