Alex
Alex

Reputation: 625

Why Django Rest serializer save doesn't work?

Example models:

I have two models, posts and comments

I want to save a comment with serializer, but it doesn't work

class Post(models.Model):
    title = models.CharField(max_length=32)
    content = models.CharField(max_length=16)

class Comment(models.Model):
    post = models.ForeignKey(
        Post, on_delete=models.CASCADE,
        related_name="comments"
    )
    title = models.CharField(max_length=32)
    comment = models.CharField(max_length=16)

This is my serializer

class CommentSerializer(serializers.ModelSerializer):
    class Meta:
        model = Comment
        fields = [
            'title',
            'comment'
        ]

Like this I'm trying to do it

# post instance

serializer = CommentSerializer(post, data=comment_data)
if serializer.is_valid(): # True
    serializer.save()

It doesn't show any error, but don't save to the database.

To solve I made a function that simulates serializer

def save_c(post, comment_data):
    # this works 
    # But I think it is better to use the serializer
    return Comment.objects.create(post=post, **comment_data)

Any suggestion? I'll be very grateful

Upvotes: 0

Views: 946

Answers (1)

VJ Magar
VJ Magar

Reputation: 1052

I think the comment serializer is working. However as no post it defined it's getting created as isolated comment (comment without post).

Here in

serializer = CommentSerializer(post, data=comment_data)

DRF is looking for comment instance, not post.

You can add product in the fields of comment serilaizer, and pass the all the details in data.

#serializer
class CommentSerializer(serializers.ModelSerializer):
    class Meta:
        model = Comment
        fields = [
            'title',
            'comment',
            'post'
        ]

#in view
serializer = CommentSerializer(data={"post": post, **comment_data}): 

Upvotes: 1

Related Questions