Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Nested manytomany relationship with serializer #3

Open
dexterm opened this issue May 17, 2019 · 0 comments
Open

Nested manytomany relationship with serializer #3

dexterm opened this issue May 17, 2019 · 0 comments

Comments

@dexterm
Copy link

dexterm commented May 17, 2019

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/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant