Reputation: 15177
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.
Upvotes: 2
Views: 1474
Reputation: 7386
There are lots of ways you could go about this, depending on a lot of information you don't give, but, perhaps look into using a SerializerMethodField in your serializer.
The basic idea would be to create a method that is able to return the appropriate URL for the thumbnail given the object instance and bind the SerializerMethodField to that.
By default DRF's GenericViews pass the request through to serializers via the context
parameter. This enables you to access the request with such as request = self.context.get('request', None)
. From there you can read the thumbnail options as you suggest.
Hopefully that's enough to get you started.
Upvotes: 2