Django DRF 和通用关系:如何从 API 响应中获取 content_object 字段?
Django DRF and generic relations: how to obtain content_object field from API response?
我已经按照官方指南在 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 请求 - 文档。
相反,该字段不可用。如果我尝试将它添加到序列化程序中列出的字段中,它会抛出错误。
我如何访问该内容,以便我知道每个文档属于哪个文件夹或哪个集合?
非常感谢。
试试这个:
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 检查返回字段的类型
我已经按照官方指南在 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 请求 - 文档。 相反,该字段不可用。如果我尝试将它添加到序列化程序中列出的字段中,它会抛出错误。
我如何访问该内容,以便我知道每个文档属于哪个文件夹或哪个集合?
非常感谢。
试试这个:
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 检查返回字段的类型