serializers.py 2.16 KB
Newer Older
1
from picampaign.campaign.models import (Campaign, CampaignContact,
2
                                        Argumentary)
3
from picampaign.contact.models import Phone
4
from picampaign.organization.serializers import GroupSerializer
Aymeric Barantal's avatar
Aymeric Barantal committed
5
6
7
from rest_framework import serializers


8
9
10
11
class ArgumentarySerializer(serializers.ModelSerializer):

    class Meta:
        model = Argumentary
12
        fields = ('text', 'title')
13

14
15
16
17
18
class PhoneSerializer(serializers.ModelSerializer):

    class Meta:
        model = Phone
        fields = ('phone',)
19

Aymeric Barantal's avatar
Aymeric Barantal committed
20
21
22
23
24
25
26
27
class CampaignSerializer(serializers.HyperlinkedModelSerializer):

    class Meta:
        model = Campaign
        fields = ('id', 'title', 'description', 'start_date', 'end_date')

class CampaignContactSerializer(serializers.HyperlinkedModelSerializer):

28
29
30
    full_name = serializers.ReadOnlyField(source='contact.full_name')
    first_name = serializers.ReadOnlyField(source='contact.first_name')
    last_name = serializers.ReadOnlyField(source='contact.last_name')
31
    phone = PhoneSerializer(many=True, source='contact.phones')
32
    groups = GroupSerializer(many=True, source='contact.groups')
33
34
    contact_id = serializers.ReadOnlyField(source='contact.id')
    photo = serializers.ReadOnlyField(source='contact.get_photo_url')
Aymeric Barantal's avatar
Aymeric Barantal committed
35
36
37

    class Meta:
        model = CampaignContact
38
        fields = ('id', 'weight', 'contact_id',
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
                  'full_name', 'first_name', 'last_name',
                  'phone', 'groups', 'photo')

    def to_representation(self, instance):
        """
        We want to validate the phone number.
        """
        # First, let's get the campaign
        data = super(CampaignContactSerializer, self).to_representation(instance)
        campaign = instance.campaign
        # We should have a filter parameter for the campaign
        filter = campaign.phone_filter
        if filter == '' or filter is None:
            # No filter, we just return the first phone number
            data['phone'] = data['phone'][0]['phone']
            return data
        else:
            for phone in data['phone']:
                if phone['phone'].startswith(filter):
                    data['phone'] = phone['phone']
                    return data