Reputation: 68
I have a tag model like this:
class Tag(models.Model):
tag = models.CharField(max_length=100)
and an image model like this:
class Image(models.Model):
image_name=models.CharField(max_length=40,unique=False)
...
tags = models.ManyToManyField(Tag)
It is currently taking the primary key of the tags table in the array instead of the string values like this:
{
"image_name" : "abc.png",
"tags" : [1, 2]
}
However, I want to be able to create a new image with POST request with multiple tags, something like this:
{
"image_name" : "abc.png",
"tags" : ["logo", "abc"]
}
When I do this, I want logo and abc to be inserted into Tags table automatically.
Is ManyToManyField correct way to do this? If so, how to achieve this?
Upvotes: 1
Views: 98
Reputation: 97
By default nested serializers are read-only. If you want to support write-operations to a nested serializer field you'll need to create create() and/or update() methods in order to explicitly specify how the child relationships should be saved
Source: https://www.django-rest-framework.org/api-guide/relations/#writable-nested-serializers
Upvotes: 1