Home > Mobile >  Django 'model' object is not iterable when response
Django 'model' object is not iterable when response

Time:11-30

i hvae 2 model. And the two models are connected to the ManyToManyField.

models.py

class PostModel(models.Model):
    id = models.AutoField(primary_key=True, null=False)
    title = models.TextField()
    comments = models.ManyToManyField('CommentModel')
class CommentModel(models.Model):
    id = models.AutoField(primary_key=True, null=False)
    post_id = models.ForeignKey(Post, on_delete=models.CASCADE)
    body = models.TextField()

and serializers.py

class CommentModel_serializer(serializers.ModelSerializer):
    class Meta:
        model = MainCommentModel
        fields = '__all__'

class PostModel_serializer(serializers.ModelSerializer):
    comment = MainCommentModel_serializer(many=True, allow_null=True, read_only=True)
    class Meta:
        model = MainModel
        fields = '__all__'

and views.py

@api_view(['GET'])
def getPost(request, pk):
    post = PostModel.objects.filter(id=pk).first()
    comment_list = CommentModel.objects.filter(post_id=post.id)
    for i in comments_list:
        post.comments.add(i)
    serializer = PostModel_serializer(post, many=True)
    return Response(serializer.data)

There is an error when I make a request.

'PostModel' object is not iterable

and The trackback points here.

return Response(serializer.data)

I tried to modify a lot of code but I can't find solutions. Please tell me where and how it went wrong

CodePudding user response:

Referring from this thread, you should remove many=True in PostModel_serializer.

Also it should be comment_list not comments_list.

@api_view(['GET'])
def getPost(request, pk):
    post = PostModel.objects.filter(id=pk).first()
    comment_list = CommentModel.objects.filter(post_id=post.id)
    for i in comment_list:
        post.comments.add(i)
    serializer = PostModel_serializer(post)
    return Response(serializer.data)

CodePudding user response:

I think you did wrong while creating ManyToManyField().

Instead of this:

comments = models.ManyToManyField('CommentModel') #Here you made mistake. you should not add single quote to CommentModel. I think that's why you got that error

Try this:

comments = models.ManyToManyField(CommentModel)
  • Related