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

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
    contact_id = serializers.ReadOnlyField(source='contact.id')
34
    email = serializers.ReadOnlyField(source='contact.mail')
35
    twitter = serializers.ReadOnlyField(source='contact.twitter')
36
    photo = serializers.ReadOnlyField(source='contact.get_photo_url')
37 38 39

    class Meta:
        model = CampaignContact
40
        fields = ('id', 'weight', 'contact_id',
41
                  'full_name', 'first_name', 'last_name',
42
                  'phone', 'groups', 'photo', 'email', 'twitter')
43 44 45 46 47 48 49 50 51 52 53

    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:
54 55
            # No filter, we return all the numbers
            data['phone'] = [a['phone'] for a in data['phone']]
56 57 58 59 60 61
            return data
        else:
            for phone in data['phone']:
                if phone['phone'].startswith(filter):
                    data['phone'] = phone['phone']
                    return data