I used django-taggit to add tags to my model. Django Version: 2.2.10, Python Version: 3.8.1
Now I'm trying to integrate tags with django rest-framework, e.g. CREATE/UPDATE/REMOVE model instances with/without tags.
My problem: I'm not able to create (via rest api) a new instance of my model with tags. I can GET model instances without problems.
My models.py:
from taggit.managers import TaggableManager
class Task(models.Model):
name = models.CharField(max_length=100, blank=False)
...
tags = TaggableManager(blank=True)
def get_tags(self):
""" names() is a django-taggit method, returning a ValuesListQuerySet
(basically just an iterable) containing the name of each tag as a string
"""
return self.tags.names()
def __str__(self):
return self.title
My serializers.py:
class TagsField(serializers.Field):
""" custom field to serialize/deserialize TaggableManager instances.
"""
def to_representation(self, value):
""" in drf this method is called to convert a custom datatype into a primitive,
serializable datatype.
In this context, value is a plain django queryset containing a list of strings.
This queryset is obtained thanks to get_tags() method on the Task model.
Drf is able to serialize a queryset, hence we simply return it without doing nothing.
"""
return value
def to_internal_value(self, data):
""" this method is called to restore a primitive datatype into its internal
python representation.
This method should raise a serializers.ValidationError if the data is invalid.
"""
return data
class TaskSerializer(serializers.ModelSerializer):
# tags field in Task model is implemented via TaggableManager class from django-taggit.
# By default, drf is not able to serialize TaggableManager to json.
# get_tags() is a method of the Task model class, which returns a Queryset containing
# the list of tags as strings. This Queryset can be serialized without issues.
tags = TagsField(source="get_tags")
class Meta:
model = Task
fields = [
"name",
...,
"tags",
]
Whenever I try to create a new instance of my Task model via POST api, I get the following error:
TypeError at /taskdrop/v1/task/
Got a `TypeError` when calling `Task.objects.create()`. This may be because you have a writable field on the serializer class that is not a valid argument to `Task.objects.create()`. You may need to make the field read-only, or override the TaskSerializer.create() method to handle this correctly.
Original exception was:
Traceback (most recent call last):
File "/home/daniele/prj/ea/TaskDrop/venv/lib/python3.8/site-packages/rest_framework/serializers.py", line 948, in create
instance = ModelClass._default_manager.create(**validated_data)
File "/home/daniele/prj/ea/TaskDrop/venv/lib/python3.8/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/daniele/prj/ea/TaskDrop/venv/lib/python3.8/site-packages/django/db/models/query.py", line 420, in create
obj = self.model(**kwargs)
File "/home/daniele/prj/ea/TaskDrop/venv/lib/python3.8/site-packages/django/db/models/base.py", line 501, in __init__
raise TypeError("%s() got an unexpected keyword argument '%s'" % (cls.__name__, kwarg))
TypeError: Task() got an unexpected keyword argument 'get_tags'
I'm kinda stuck right now...the field is definitely not read-only and regarding overriding the TaskSerializer.create() method, I don't know precisely how to do that.
Plus, I'm a bit confused about TagsField(serializers.Field) vs .create() method override. From my understanding, if I create a custom serializers field, there should be no additional need to override .create().
Finally, I tried to use django-taggit-serializer without success: the model gets created but the passed tags are just missing.
How can I fix this? Thanks.