4bb44dcb9199879cc9838e4be10057173a7e1967
[wolnelektury.git] / src / api / fields.py
1 from rest_framework import serializers
2 from django.core.urlresolvers import reverse
3
4
5 class AbsoluteURLField(serializers.ReadOnlyField):
6     def __init__(self, view_name=None, view_args=None, source='get_absolute_url', *args, **kwargs):
7         if view_name is not None:
8             source = '*'
9         super(AbsoluteURLField, self).__init__(*args, source=source, **kwargs)
10         self.view_name = view_name
11         self.view_args = {}
12         if view_args:
13             for v in view_args:
14                 fields = v.split(':', 1)
15                 self.view_args[fields[0]] = fields[1] if len(fields)>1 else fields[0]
16
17     def to_representation(self, value):
18         if self.view_name is not None:
19             kwargs = {
20                 arg: getattr(value, field)
21                 for (arg, field) in self.view_args.items()
22             }
23             value = reverse(self.view_name, kwargs=kwargs)
24         return self.context['request'].build_absolute_uri(value)
25
26
27 class LegacyMixin(object):
28     def to_representation(self, value):
29         value = super(LegacyMixin, self).to_representation(value)
30         non_null_fields = getattr(getattr(self, 'Meta', None), 'legacy_non_null_fields', [])
31         for field in non_null_fields:
32             if field in value and value[field] is None:
33                 value[field] = ''
34         return value