More views in DRF.
[wolnelektury.git] / src / catalogue / api / fields.py
1 from rest_framework import serializers
2 from sorl.thumbnail import default
3 from catalogue.models import Book
4
5
6 class BookLiked(serializers.ReadOnlyField):
7     def __init__(self, source='pk', **kwargs):
8         super(BookLiked, self).__init__(source=source, **kwargs)
9
10     def to_representation(self, value):
11         request = self.context['request']
12         if not hasattr(request, 'liked_books'):
13             if request.user.is_authenticated():
14                 request.liked_books = set(Book.tagged.with_any(request.user.tag_set.all()).values_list('id', flat=True))
15             else:
16                 request.liked_books = None
17         if request.liked_books is not None:
18             return value in request.liked_books
19
20
21 class ThumbnailField(serializers.FileField):
22     def __init__(self, geometry, *args, **kwargs):
23         self.geometry = geometry
24         super(ThumbnailField, self).__init__(*args, **kwargs)
25         
26     def to_representation(self, value):
27         if value:
28             return super(ThumbnailField, self).to_representation(
29                 default.backend.get_thumbnail(value, self.geometry)
30             )