2016-03-04 101 views
1

据我所知,如果我想获得一个嵌入资源,需要在适当的序列化器中定义它。那么无论我需要与否,它都会一直嵌入。 如果我想要两个不同的嵌入预测,我需要两个网址。如何在没有在Django REST框架中定义序列化程序的情况下获得嵌入资源?

所以我想如果像Eve做我可以实现一个?embedded=要求: GET (/emails/<id>/?embedded={"author":1},嵌入的资源只有通过默认读取。

+1

我不认为这有一个内置的功能。但你应该能够很容易地实现这一点。这可能是一个很好的起点:http://www.django-rest-framework.org/api-guide/serializers/#dynamically-modifying-fields – ilse2005

回答

1

假设你希望有不同的对象嵌入,可以实现这样想的东西,如下列:

你可以通过你的kwargs以串行的context

serializer = YourSerializer(data=initial_first_shop_data, 
          context={"author": 1}) 

,然后覆盖.to_representation()方法

def to_representation(self, instance): 
    representation = super(DynamicFieldsModelSerializer, self).to_representation(instance) 

    if 'author' in self.context: 
     author = AuthorSerializer(Author.objects.get(pk=self.context['author'])) 
     representation['author'] = author.data 

    return representation 

如果您将始终有author作为嵌入o如果它不在context中,将它添加到序列化程序并将其作为我们的情况会更简单。

+0

'author'不是唯一需要自动包含的字段,它是只是一个例子,但这个答案已经足够了。另一方面 – kxxoling

+0

,我需要在服务器端配置这不是在浏览器端自动设置? – kxxoling

+0

@kxxoling,如果你不在服务器端实现这一点,你将会遇到很多安全问题。 – DevilPinky

相关问题