serializers.py 1.37 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

    def validate(self, attrs):
36
        if attrs.get('member') and attrs.get('name'):
37
38
39
40
            raise ValidationError({
                'member': _('Either specify a member or a name'),
                'name': _('Either specify a member or a name'),
            })
41
        if not (attrs.get('member') or attrs.get('name')) and not self.partial:
42
43
            attrs['member'] = self.context['request'].member
        return super().validate(attrs)