Last Piston view replaced using OAuthlib.
[wolnelektury.git] / src / catalogue / api / fields.py
1 # -*- coding: utf-8 -*-
2 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
3 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
4 #
5 from rest_framework import serializers
6 from catalogue.models import Book
7
8
9 class BookLiked(serializers.ReadOnlyField):
10     def __init__(self, source='pk', **kwargs):
11         super(BookLiked, self).__init__(source=source, **kwargs)
12
13     def to_representation(self, value):
14         request = self.context['request']
15         if not hasattr(request, 'liked_books'):
16             if request.user.is_authenticated():
17                 request.liked_books = set(Book.tagged.with_any(request.user.tag_set.all()).values_list('id', flat=True))
18             else:
19                 request.liked_books = None
20         if request.liked_books is not None:
21             return value in request.liked_books