2

My case is basic: I want to send urls of thumbnails to the client within responses to AJAX requests. I have custom image fields that deserialize base64 encoded images from the client and sorl_thumbnail as thumbnail engine. In my views I want to instantiate deserializer with arbitrary options for thumbnailer.

What is a common techniques for that in Django REST framework?

upd
The main problem is how to pass arguments about dimensions, format, quality, etc, to serializer? In one place I might need small thumbnail of the picture, in other bigger thumbnail.

Now I see two approaches:
- Make a factory which will produce serializer with given options for thumbnail-fields
- Send thumbnail options within AJAX requests and make serializer able to read and follow them.

4

1 回答 1

2

有很多方法可以解决这个问题,具体取决于您没有提供的大量信息,但是,也许考虑在您的序列化程序中使用SerializerMethodField

基本思想是创建一个方法,该方法能够为给定对象实例的缩略图返回适当的 URL,并将 SerializerMethodField 绑定到该方法。

默认情况下,DRF 的GenericViews通过context参数将请求传递给序列化程序。这使您可以使用诸如 访问请求request = self.context.get('request', None)。从那里您可以按照您的建议阅读缩略图选项。

希望这足以让你开始。

于 2013-09-19T07:02:51.857 回答