-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathserializers.py
80 lines (62 loc) · 2.67 KB
/
serializers.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
from django.utils import translation
from rest_framework import serializers
from adhocracy4.categories.models import Category
from .models import Proposal
class CategoryField(serializers.Field):
def to_internal_value(self, category):
if category:
return Category.objects.get(pk=category)
else:
return None
def to_representation(self, category):
return {'id': category.pk, 'name': category.name}
class ProposalSerializer(serializers.ModelSerializer):
creator = serializers.SerializerMethodField()
comment_count = serializers.SerializerMethodField()
positive_rating_count = serializers.SerializerMethodField()
negative_rating_count = serializers.SerializerMethodField()
category = CategoryField()
url = serializers.SerializerMethodField()
locale = serializers.SerializerMethodField()
class Meta:
model = Proposal
fields = ('budget', 'category', 'comment_count', 'created', 'creator',
'is_archived', 'name', 'negative_rating_count',
'positive_rating_count', 'url', 'pk', 'moderator_feedback',
'moderator_feedback_choices', 'locale')
read_only_fields = ('budget', 'category', 'comment_count', 'created',
'creator', 'is_archived', 'name',
'negative_rating_count', 'positive_rating_count',
'url', 'pk', 'moderator_feedback',
'moderator_feedback_choices', 'locale')
def get_creator(self, proposal):
return proposal.creator.username
def get_comment_count(self, proposal):
if hasattr(proposal, 'comment_count'):
return proposal.comment_count
else:
return 0
def get_positive_rating_count(self, proposal):
if hasattr(proposal, 'positive_rating_count'):
return proposal.positive_rating_count
else:
return 0
def get_negative_rating_count(self, proposal):
if hasattr(proposal, 'negative_rating_count'):
return proposal.negative_rating_count
else:
return 0
def get_url(self, proposal):
return proposal.get_absolute_url()
def get_moderator_feedback(self, proposal):
if hasattr(proposal, 'moderator_feedback'):
return proposal.moderator_feedback
else:
return None
def get_moderator_feedback_choices(self, proposal):
if hasattr(proposal, 'moderator_feedback_choices'):
return proposal.moderator_feedback_choices
else:
return None
def get_locale(self, proposal):
return translation.get_language()