serializers.py 2.12 KB
Newer Older
1
import six
luxcem's avatar
luxcem committed
2
from rest_framework import serializers
3
4
from taggit_serializer.serializers import (TagListSerializerField,
                                           TaggitSerializer)
luxcem's avatar
luxcem committed
5
6
7

from rp.models import Article

8

9
10
11
12
13
14
class ArticleTagListSerializerField(TagListSerializerField):
    # We need this to fix a serializer issue:
    # https://stackoverflow.com/questions/52695298/using-django-taggit-and-django-taggit-serializer-with-issue
    def to_internal_value(self, value):
        if isinstance(value, six.string_types):
            value = value.split(',')
luxcem's avatar
luxcem committed
15

16
17
18
19
20
21
22
23
24
        if not isinstance(value, list):
            self.fail('Not a list', input_type=(value).__name__)

        for s in value:
            if not isinstance(s, six.string_types):
                self.fail('Not a string')

            self.child.run_validation(s)
        return value
Okhin's avatar
Okhin committed
25

26
27
28
29
    def to_representation(self, obj):
        if not isinstance(obj, list):
            return [tag.name for tag in obj.all()]
        return obj
30

31

32
class ArticleSerializer(TaggitSerializer, serializers.ModelSerializer):
33
    #: List of short tags to describe the article (eg. "Privacy", "Copyright")
34
    tags = TagListSerializerField(help_text="""
35
        List of short tags to describe the article (eg."Privacy", "Copyright").
36
        It must be a valid JSON list of tags.
37

38
39
        For instance ["Privacy", "Copyright"}]
        """, required=False)
40

luxcem's avatar
luxcem committed
41
42
    class Meta:
        model = Article
43
        fields = ('id', 'url', 'title', 'tags', 'extracts',
44
45
                  'status', 'score', 'priority',
                  'archive', 'quote', 'speak')
46

Okhin's avatar
Okhin committed
47
    def create(self, validated_data):
48
        article = Article.add_new_url(**validated_data)
49
50
        if article is not None:
            article.save()
Okhin's avatar
Okhin committed
51
        return article
52
53

    def update(self, instance, validated_data):
54
        tags = validated_data.pop("tags", None)
55
56
57
58
59
60
61

        # Let's update the classic fields of the
        # instance first
        for (k, v) in validated_data.items():
            setattr(instance, k, v)

        # Let's set the tags to what's provided
62
63
        if tags:
            instance.tags.set(*tags)
64
65
        instance.save()
        return instance