# Create a Book instance with multiple tags in Django REST Framework

**URL:** https://forum.djangoproject.com/t/create-a-book-instance-with-multiple-tags-in-django-rest-framework/19284
**Category:** Getting Started
**Created:** [March 5, 2023, 4:50pm UTC](https://forum.djangoproject.com/t/create-a-book-instance-with-multiple-tags-in-django-rest-framework/19284 "2023-03-05T16:50:15Z")
**Posts on this page:** 7
**Page:** 1

<div class="post-metadata">

### Author: ![mizanur-16](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/mizanur-16/32/12527_2.png) [@mizanur-16](https://forum.djangoproject.com/u/mizanur-16)
#### Post date: [March 5, 2023, 4:50pm UTC](https://forum.djangoproject.com/t/create-a-book-instance-with-multiple-tags-in-django-rest-framework/19284/1 "2023-03-05T16:50:15Z")

</div>

I am new to Django and I have created 2 models named ‘Book’ and ‘Tag’ and I tried this way-

**Model Class**

```auto
class Tag(models.Model):

    name = models.CharField(max_length=50, unique=True)

    def __str__ (self):
        return self.name + '___'

class Book(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    title = models.CharField(max_length=100)
    tags = models.ManyToManyField(Tag)

    def __str__ (self):
        return self.title

```

**Searializer Class**

```auto
class TagSerializer(serializers.ModelSerializer):

    class Meta:
        model = Tag
        fields = ['id', 'name']

class BookSerializer(serializers.ModelSerializer):
    tags = serializers.ListField(child=serializers.CharField())

    class Meta:
        model = Book
        fields = ['id', 'title', 'tags']

    def save(self, **kwargs):
        tags = self.validated_data.pop('tags', [])
        book = BookModel.objects.create(**self.validated_data)

        if len(tags):
            tag_objs = []
            for tag_name in tags:
                tag_obj, created = Tag.objects.get_or_create(name=tag_name)
                tag_objs.append(tag_obj)
                book.tags.add(tag_obj) # Having an error in this line

```

**View Class**

```auto
class BookList(APIView):
    """List all Book and create new one in Book app"""

    def get(self, request, format=None):
        book = Book.objects.all()
        serializer = BookSerializer(book, many=True)

        return Response(serializer.data, status=status.HTTP_200_OK)

    def post(self, request, format=None):
        data = request.data

        serializer = BookSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

```

Here, My request body will be-

```auto
{
    title: 'Essential English Grammar',
    tags: ['lesson', 'english']
}

```

And I need the following response with get request-

```auto
{
    id: UUID
    title: 'Essential English Grammar',
    tags: ['lesson', 'english']
}

```

I need reverse relationship means I will be able to fetch all Books with a Tag. Please help me to solve this problem

---

<div class="post-metadata">

### Author: ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)
#### Post date: [March 5, 2023, 5:26pm UTC](https://forum.djangoproject.com/t/create-a-book-instance-with-multiple-tags-in-django-rest-framework/19284/2 "2023-03-05T17:26:04Z")

</div>

ManyToMany relationships work the same and equally well in both directions.

Review the docs and examples at [Many-to-many relationships | Django documentation | Django](https://docs.djangoproject.com/en/4.1/topics/db/examples/many_to_many/)

---

<div class="post-metadata">

### Author: ![mizanur-16](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/mizanur-16/32/12527_2.png) [@mizanur-16](https://forum.djangoproject.com/u/mizanur-16)
#### Post date: [March 5, 2023, 5:39pm UTC](https://forum.djangoproject.com/t/create-a-book-instance-with-multiple-tags-in-django-rest-framework/19284/3 "2023-03-05T17:39:49Z")

</div>

Thanks sir, I have used Many-to-many relationship. But a problem I am facing in the Serializer’s save method. I mentioned with # comment. Could you please solve this issue?

---

<div class="post-metadata">

### Author: ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)
#### Post date: [March 5, 2023, 5:41pm UTC](https://forum.djangoproject.com/t/create-a-book-instance-with-multiple-tags-in-django-rest-framework/19284/4 "2023-03-05T17:41:44Z")

</div>

What is the specific error you are receiving? Please post the traceback.

---

<div class="post-metadata">

### Author: ![mizanur-16](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/mizanur-16/32/12527_2.png) [@mizanur-16](https://forum.djangoproject.com/u/mizanur-16)
#### Post date: [March 5, 2023, 5:51pm UTC](https://forum.djangoproject.com/t/create-a-book-instance-with-multiple-tags-in-django-rest-framework/19284/5 "2023-03-05T17:51:06Z")

</div>

**Error:**  
“Got KeyError when attempting to get a value for field `tags` on serializer `BookSerializer`.\nThe serializer field might be named incorrectly and not match any attribute or key on the `OrderedDict` instance.\nOriginal exception text was: ‘tags’.”

**Serializer class**

```auto
book.tags.add(tag_obj) # Having an error in this line

```

Here I guess, tag\_obj is being added to the book instance (id: uuid, tag: something) but I want my response model like,

```auto
{ ....
    tags: ['lesson']
}

```

not

```auto
tags: {
            id: uuid,
            name: 'lesson'
          }

```

Thanks for your kind response sir.

---

<div class="post-metadata">

### Author: ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)
#### Post date: [March 5, 2023, 6:20pm UTC](https://forum.djangoproject.com/t/create-a-book-instance-with-multiple-tags-in-django-rest-framework/19284/6 "2023-03-05T18:20:10Z")

</div>

Please post the complete traceback from the error message you’re receiving.

---

<div class="post-metadata">

### Author: ![aghosh0605](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/aghosh0605/32/14025_2.png) [@aghosh0605](https://forum.djangoproject.com/u/aghosh0605)
#### Post date: [June 3, 2023, 1:49pm UTC](https://forum.djangoproject.com/t/create-a-book-instance-with-multiple-tags-in-django-rest-framework/19284/7 "2023-06-03T13:49:02Z")

</div>

Before they can be related in a many-to-many relationship, both records must exist in the database. That is why the error is coming.

 ![image](https://us1.discourse-cdn.com/flex026/uploads/djangoproject/original/2X/b/bb7b032bb54857e401f6fc2848fc3ea407d9014d.png)  
These types of errors will come. Check once both values are saved in the database before making the relationship. Let me know if it’s fixed or not…  
Check the documentation [here](https://docs.djangoproject.com/en/4.1/topics/db/examples/many_to_many/)
