aarav-tech / ems

Employee Management System

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Nested manytomany relationship with serializer

dexterm opened this issue · comments

Hi,
can you suggest how to handle manytomany relationship

I have the following models
#this model can be associated with more than 1 post
class Category(models.Model):
title = models.CharField(max_length=255,unique=True, blank=False, null=False)

#this model can be associated with more than 1 category
class Post(models.Model):
# post title
title = models.CharField(max_length=255, null=False)
content = models.TextField(null = False, max_length=12000)
slug = models.CharField(max_length=255, null=False, unique=True)
categories = models.ManyToManyField(Category, related_name='categories')

Can you please advise how to write a serializer that posts new data.

class PostCategorySerializer(serializers.ModelSerializer):

class Meta:
    model = Category
    read_only_fields = ('id',)
    exclude = ('title','created_by')

class PostSerializer(serializers.ModelSerializer):
created_by_id = serializers.PrimaryKeyRelatedField(
queryset=User.objects.all(), source='created_by', write_only=True, required=False)
categories = PostCategorySerializer(many=True)

class Meta:
    model = Post
    fields = ('title', 'content', 'slug', 'categories', 'created_by_id')

def create(self, validated_data):
    #before saving the post remove the field categories to avoid errors
    categories = validated_data.pop('categories')
    post = Post.objects.create(**validated_data)
    for cat in categories:
        Category.objects.create(**cat, categories=post)
    return post

When I make the api request the post is created in the database but the categories are not associated

curl -H "Authorization: Bearer HKAEKzMg278hjsMVYYPlCdq6OqFA21" -X POST -H 'Content-Type: application/json' -d '{"title":"My first post","content":"My first post", "slug":"my-first-post", "short_description":"my first post....", "categories":[{"id":2, "title":"Python"}], "created_by":"2", "created_by_id":"2"}' http://localhost:8000/api/v1/posts/