serializers.py 1.62 KB
Newer Older
1
from django.utils.translation import ugettext_lazy as _
Gijs Hendriksen's avatar
Gijs Hendriksen committed
2
from rest_framework import serializers
3
from rest_framework.exceptions import ValidationError
Gijs Hendriksen's avatar
Gijs Hendriksen committed
4
5

from pizzas.models import Product, PizzaEvent, Order
6
from pizzas.services import can_change_order
Gijs Hendriksen's avatar
Gijs Hendriksen committed
7
8
9
10
11
12
13
14
15


class PizzaSerializer(serializers.ModelSerializer):
    class Meta:
        model = Product
        fields = ('pk', 'name', 'description', 'price', 'available')


class PizzaEventSerializer(serializers.ModelSerializer):
16
17
18
    class Meta:
        model = PizzaEvent
        fields = ('start', 'end', 'event', 'title', 'is_admin')
19
20

    event = serializers.PrimaryKeyRelatedField(read_only=True)
21
    is_admin = serializers.SerializerMethodField('_is_admin')
22

23
24
25
    def _is_admin(self, instance):
        member = self.context['request'].member
        return can_change_order(member, instance)
Gijs Hendriksen's avatar
Gijs Hendriksen committed
26
27
28
29
30
31
32
33
34
35
36
37
38


class OrderSerializer(serializers.ModelSerializer):
    class Meta:
        model = Order
        fields = ('pk', 'paid', 'product', 'name', 'member')
        read_only_fields = ('pk', 'paid', 'name', 'member')


class AdminOrderSerializer(serializers.ModelSerializer):
    class Meta:
        model = Order
        fields = ('pk', 'paid', 'product', 'name', 'member')
39
40

    def validate(self, attrs):
41
        if attrs.get('member') and attrs.get('name'):
42
43
44
45
            raise ValidationError({
                'member': _('Either specify a member or a name'),
                'name': _('Either specify a member or a name'),
            })
46
        if not (attrs.get('member') or attrs.get('name')) and not self.partial:
47
48
            attrs['member'] = self.context['request'].member
        return super().validate(attrs)