【发布时间】:2015-09-02 12:56:40
【问题描述】:
在我的页面序列化器PageSerializer 中,如下所示,我想从 Collection 和
显示嵌套在 PageSerializer 中的所有集合项(多对多)。
我想实现这样的输出......
"results": [
{
"url": "http://127.0.0.1:8000/v1/page/00c8015e-9b03...",
"title": "Test Page",
"collections":
{
"title": "Test Collection",
[
{
"image": "http://www.demo.com/test.png",
"video": None
},
{
"image": None,
"video": "http://www.demo.com/test.mpeg"
}
]
}
}
]
}
这就是我现在拥有的......
class Page(models.Model):
title = models.CharField(max_length=80)
class PageSerializer(serializers.ModelSerializer):
class Meta:
model = Page
fields = ("title", )
class Collection(models.Model):
title = models.CharField(max_length=80, help_text="Title of collection")
content_type = models.ForeignKey(ContentType)
object_id = models.UUIDField()
content_object = generic.GenericForeignKey('content_type', 'object_id')
collection_items = models.ManyToManyField('collections.CollectionItem')
class CollectionItem(models.Model):
image = models.ImageField(upload_to='/test')
video = models.URLField(max_length=512, blank=True, null=True)
因为通用关系在集合模型上如何在 DRF 中完成?
我正在考虑在 Page 模型本身上创建一个方法来获取数据并将其添加到序列化程序中。
我确信有更好的方法。我看过http://www.django-rest-framework.org/api-guide/relations/#generic-relationships 但它只描述了以相反的方式建立关系。
【问题讨论】:
标签: python django python-3.x django-models django-rest-framework