serializers.py 2.34 KB
Newer Older
Sébastiaan Versteeg's avatar
Sébastiaan Versteeg committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from rest_framework import serializers

from thaliawebsite.api.services import create_image_thumbnail_dict
from photos import services
from photos.models import Photo, Album


class PhotoRetrieveSerializer(serializers.ModelSerializer):
    file = serializers.SerializerMethodField('_file')

    def _file(self, obj):
        file = None
        if obj:
            file = obj.file
        return create_image_thumbnail_dict(
Sébastiaan Versteeg's avatar
Sébastiaan Versteeg committed
16
            self.context['request'], file, fit_large=False)
Sébastiaan Versteeg's avatar
Sébastiaan Versteeg committed
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58

    class Meta:
        model = Photo
        fields = ('pk', 'rotation', 'hidden', 'album', 'file')


class PhotoCreateSerializer(serializers.ModelSerializer):
    class Meta:
        model = Photo
        fields = ('pk', 'rotation', 'hidden', 'album', 'file')


class AlbumSerializer(serializers.ModelSerializer):
    photos = serializers.SerializerMethodField('_photos')
    accessible = serializers.SerializerMethodField('_accessible')

    def _accessible(self, obj):
        return services.is_album_accessible(self.context['request'], obj)

    def _photos(self, obj):
        if self._accessible(obj):
            return PhotoRetrieveSerializer(obj.photo_set,
                                           context=self.context,
                                           many=True).data
        return []

    def create(self, validated_data):
        photos_data = validated_data.pop('photos')
        album = Album.objects.create(**validated_data)
        for photo_data in photos_data:
            Photo.objects.create(album=album, **photo_data)
        return album

    def update(self, instance, validated_data):
        photos_data = validated_data.pop('photos')
        album = Album.objects.update(**validated_data)
        for photo_data in photos_data:
            Photo.objects.update(album=album, **photo_data)
        return album

    class Meta:
        model = Album
59
        fields = ('pk', 'title', 'date', 'hidden', 'shareable',
Sébastiaan Versteeg's avatar
Sébastiaan Versteeg committed
60
61
62
63
64
65
66
67
68
69
70
71
                  'accessible', 'photos')


class AlbumListSerializer(serializers.ModelSerializer):
    cover = PhotoRetrieveSerializer()
    accessible = serializers.SerializerMethodField('_accessible')

    def _accessible(self, obj):
        return services.is_album_accessible(self.context['request'], obj)

    class Meta:
        model = Album
72
        fields = ('pk', 'title', 'date', 'hidden', 'shareable',
Sébastiaan Versteeg's avatar
Sébastiaan Versteeg committed
73
                  'accessible', 'cover')