import six from rest_framework import serializers from taggit_serializer.serializers import (TagListSerializerField, TaggitSerializer) from rp.models import Article 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(',') 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 def to_representation(self, obj): if not isinstance(obj, list): return [tag.name for tag in obj.all()] return obj class ArticleSerializer(TaggitSerializer, serializers.ModelSerializer): #: List of short tags to describe the article (eg. "Privacy", "Copyright") tags = TagListSerializerField(help_text=""" List of short tags to describe the article (eg."Privacy", "Copyright"). It must be a valid JSON list of tags. For instance ["Privacy", "Copyright"}] """, required=False) class Meta: model = Article fields = ('id', 'url', 'title', 'tags', 'extracts', 'status', 'score', 'priority', 'archive', 'quote', 'speak') def create(self, validated_data): article = Article.add_new_url(**validated_data) if article is not None: article.save() return article def update(self, instance, validated_data): tags = validated_data.pop("tags", None) # 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 if tags: instance.tags.set(*tags) instance.save() return instance