serializers.py 1.08 KB
Newer Older
luxcem's avatar
luxcem committed
1 2
from rest_framework import serializers

3
from taggit.managers import TaggableManager
luxcem's avatar
luxcem committed
4 5
from rp.models import Article

6

7 8 9 10 11 12 13 14
class TagListSerializer(serializers.Field):
    class Meta:
        model = TaggableManager(blank=True)

    def to_representation(self, obj):
        if type(obj) is not list:
            return [tag.name for tag in obj.all()]
        return obj
luxcem's avatar
luxcem committed
15

16 17 18
    def to_internal_value(self, data):
        return [tag.strip() for tag in data.split(",")]

19

luxcem's avatar
luxcem committed
20
class ArticleSerializer(serializers.ModelSerializer):
21 22
    #: List of short tags to describe the article (eg. "Privacy", "Copyright")
    tags = TagListSerializer(help_text="""
23 24
        List of short tags to describe the article (eg."Privacy, Copyright").
        Must be a list of tags, coma separated (or an empty string).
25
        """, default="")
26

luxcem's avatar
luxcem committed
27 28
    class Meta:
        model = Article
29
        fields = ('id', 'url', 'title', 'tags', 'extracts', 'status', 'score')
30

okhin's avatar
okhin committed
31
    def create(self, validated_data):
32
        article = Article.add_new_url(**validated_data)
33 34
        if article is not None:
            article.save()
okhin's avatar
okhin committed
35
        return article