serializers.py 1.33 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
6
7
8
9
10
11
12
13
14

from pizzas.models import Product, PizzaEvent, Order


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


class PizzaEventSerializer(serializers.ModelSerializer):
15
16
17

    event = serializers.PrimaryKeyRelatedField(read_only=True)

Gijs Hendriksen's avatar
Gijs Hendriksen committed
18
19
    class Meta:
        model = PizzaEvent
20
        fields = ('start', 'end', 'event', 'title')
Gijs Hendriksen's avatar
Gijs Hendriksen committed
21
22
23
24
25
26
27
28
29
30
31
32
33


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')
34
35
36
37
38
39
40
41
42
43

    def validate(self, attrs):
        if attrs['member'] and attrs['name']:
            raise ValidationError({
                'member': _('Either specify a member or a name'),
                'name': _('Either specify a member or a name'),
            })
        if not (attrs['member'] or attrs['name']):
            attrs['member'] = self.context['request'].member
        return super().validate(attrs)