在下面显示的页面序列化器PageSerializer中,我想从Collection和
显示嵌套在PageSerializer中的所有Collection Items(多对多)。

我想实现类似这样的输出...。

"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
但这只是描述了如何建立关系。

最佳答案

例如,在Page模型上创建一个GenericRelation

class Page(models.Model):
     title = models.CharField(max_length=80)
     stuff = GenericRelation('app_name_model_here')


然后像这样使用嵌套的序列化程序...

class PageSerializer(serializers.ModelSerializer):
    stuff = YOURColltionserializer(many=True)
    class Meta:
        model = Page
        fields = ("title", "stuff" )


一旦定义了YOURColltionserializer,它将按例外方式工作。

关于python - 为逆向遗传关系创建序列化器,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32353819/

10-14 19:21
查看更多