0

I want my comment serializer response to be like this -

[      
{
    "id": 50,
    "comment": "50Reply1",
    "timestamp": "2021-05-20 00:26:41",
    "user": {
        "hnid": "d0a04c7b-6399-44db-ba7c-4ef39ae7e59c",
        "username": "Sunasuns #GD6GXAJ4",
        "profile_img": "/media/Bay-Morning-Sea-Clouds-Beach-House-Wallpaper-1162x768.jpg",
        "full_name": "Suna suns"
    },
    "reply_comment": 
    {
      "id": 51,
      "comment": "50Reply2",
      "timestamp": "2021-05-20 00:26:46",
      "user": {
        "hnid": "d0a04c7b-6399-44db-ba7c-4ef39ae7e59c",
        "username": "Sunasuns #GD6GXAJ4",
        "profile_img": "/media/Bay-Morning-Sea-Clouds-Beach-House-Wallpaper-1162x768.jpg",
        "full_name": "Suna suns"
      },
     "reply_comment": 50
},
    {
    "id": 52,
    "comment": "50Reply3",
    "timestamp": "2021-05-20 00:26:51",
    "user": {
        "hnid": "d0a04c7b-6399-44db-ba7c-4ef39ae7e59c",
        "username": "Sunasuns #GD6GXAJ4",
        "profile_img": "/media/Bay-Morning-Sea-Clouds-Beach-House-Wallpaper-1162x768.jpg",
        "full_name": "Suna suns"
    },
    "reply_comment": 50
 },
}]

enter image description here

But instead I am getting something like this -

[    {
        "id": 52,
        "comment": "50Reply2",
        "timestamp": "2021-05-20 00:26:46",
        "user": {
            "hnid": "d0a04c7b-6399-44db-ba7c-4ef39ae7e59c",
            "username": "Sunasuns #GD6GXAJ4",
            "profile_img": "/media/Bay-Morning-Sea-Clouds-Beach-House-Wallpaper-1162x768.jpg",
            "full_name": "Suna suns"
        },
        "reply_comment": 50
    },
    {
        "id": 51,
        "comment": "50Reply1",
        "timestamp": "2021-05-20 00:26:41",
        "user": {
            "hnid": "d0a04c7b-6399-44db-ba7c-4ef39ae7e59c",
            "username": "Sunasuns #GD6GXAJ4",
            "profile_img": "/media/Bay-Morning-Sea-Clouds-Beach-House-Wallpaper-1162x768.jpg",
            "full_name": "Suna suns"
        },
        "reply_comment": 50
    },
    {
        "id": 50,
        "comment": "Reply3",
        "timestamp": "2021-05-20 00:24:51",
        "user": {
            "hnid": "d0a04c7b-6399-44db-ba7c-4ef39ae7e59c",
            "username": "Sunasuns #GD6GXAJ4",
            "profile_img": "/media/Bay-Morning-Sea-Clouds-Beach-House-Wallpaper-1162x768.jpg",
            "full_name": "Suna suns"
        },
        "reply_comment": null
    },]

Here is my model.py

class Comment(models.Model):

    post = models.ForeignKey(Posts, related_name='comments', on_delete=models.CASCADE)
    user = models.ForeignKey(HNUsers, related_name='comments', on_delete=models.CASCADE)
    comment = models.TextField("Comment", blank=True, null=True)
    timestamp = models.DateTimeField("Timestamp", blank=True, null=True, auto_now_add=True)
    reply_comment = models.ForeignKey('self', related_name='replies', on_delete=models.CASCADE, blank=True, null=True)

    class Meta:
        verbose_name_plural = "Comments"

My get views.py

  if request.method == 'GET':
        data = request.data
        comments = Comment.objects.filter(post_id=data['post']).order_by('-timestamp')
        print(comments)
        serializer = CommentGetValueSerializer(comments, many=True)
        print("print ", serializer)
    return Response(serializer.data, status=status.HTTP_201_CREATED)

My get serializers.py

class CommentUserSerializer(serializers.ModelSerializer):
    class Meta:
        model = HNUsers
        fields = (
            'hnid',
            'username',
            'profile_img',
            'full_name',
        )

class CommentGetValueSerializer(serializers.ModelSerializer):
    user = CommentUserSerializer(read_only=True, many=False)
    timestamp = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S")
    # reply_comment = serializers.SerializerMethodField()
    #comments = serializers.SerializerMethodField()

    class Meta:
        model = Comment
        fields = (
            'id',
            'comment',
            'timestamp',
            'user',
            'reply_comment'
        )

Any help regarding this is much appreciated .

Mitesh
  • 1,544
  • 3
  • 13
  • 26

2 Answers2

1

As I understand from your last comment on your question that you'd like to get the details of reply_comment instead of it's ID.

For this, you can simply use "depth" in your ModelSerializer in order to get the details of the foreign-key linked object like below:

class CommentGetValueSerializer(serializers.ModelSerializer):
    user = CommentUserSerializer(read_only=True, many=False)
    timestamp = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S")

    class Meta:
        model = Comment
        fields = (
            'id',
            'comment',
            'timestamp',
            'user',
            'reply_comment'
        )
        depth = 1
KutayAslan
  • 494
  • 6
  • 13
  • Hi, Thanks a ton for your answer. I actually tried this but it solves my problem partially . For example, if i put depth = 1 than I will have that post in return. but all I want is , the parent post say id : 50 first than all the replies under reply_comment : say id 51 and so on – Mitesh May 20 '21 at 07:22
  • Hmm, I see. Then you may need to return related objects of the foreign key. So in your CommentGetValueSerializer; changing 'reply_comment' to 'replies' should be enough. – KutayAslan May 20 '21 at 07:29
  • I think I got it ... Thanks a ton .. But now I am getting comment id 51 .. 52 separately as well as in the replies section.. I dont want replies in separately . How can I do this ? – Mitesh May 20 '21 at 07:35
  • I changed my query Comment.objects.filter(post_id=data['post']).order_by('-timestamp') to Comment.objects.filter(post_id=data['post'], reply_comment=None).order_by('-timestamp') and It works like a charm .. Thanks a lot man – Mitesh May 20 '21 at 07:42
0

So, normally, we can do something like this to show related models to a particular model:

class CommentGetValueSerializer(serializers.ModelSerializer):
    user = CommentUserSerializer(read_only=True, many=False)
    timestamp = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S")
    replies = SomeCommentSerializer(many=True, read_only=True)

replies is a related name of comments replies to a particular comment.

But, in your case, I guess you're expecting the same format for each reply and we cannot reference the same class in its class. So here's:

class CommentGetValueSerializer(serializers.ModelSerializer):
    user = CommentUserSerializer(read_only=True, many=False)
    timestamp = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S")

    class Meta:
        fields = (..., 'replies')

    def get_fields(self):
        fields = super(CategorySerializer, self).get_fields()
        fields['replies'] = CommentGetValueSerializer(many=True, read_only=True)
        return fields

See this answer for a reference.

Please also beware of the infinity loop since this is a recursive call :)

Preeti Y.
  • 429
  • 4
  • 11