JSON object with multiple Models

hi,I’ve been trying to make a blog rest -api ,
I don’t know if this is a good idea to deal with Json object,
but is there anyway I can make json object that contain all post fields, and a field called comment that has all comments object that are relatable to the post?

models.py

class Post(models.Model):
    content = models.CharField(max_length=400, null=False)
    date = models.DateTimeField(auto_now=True)
    author = models.ForeignKey(User, on_delete=models.CASCADE, null=False)
    image = models.ImageField(null=True, blank=True)

    def likes_count(self):
        return len(Likes.objects.filter(post=self))

    def comments_count(self):
        return len(Comment.objects.filter(post=self))

    def __str__(self):
        return self.content




class Comment(models.Model):
    post = models.ForeignKey(Post, on_delete=models.CASCADE, null=False)
    user = models.ForeignKey(User, on_delete=models.CASCADE, null=False)
    date = models.DateTimeField(auto_now=True)
    like = models.IntegerField(blank=True, null=True)
    content = models.CharField(max_length=300, null=False)

    def __str__(self):
        return self.content

serializers.py

class PostSerializers(serializers.ModelSerializer):
    class Meta:
        model = Post
        fields = [
            "id",
            "content",
            "date",
            "author",
            "image",
            "likes_count",
            "comments_count",
        ]


class CommentSerializers(serializers.ModelSerializer):
    class Meta:
        model = Comment
        fields = "__all__"

See the docs for Dealing with nested objects

This is a side note. Instead of doing

len(Likes.objects.filter(post=self))

I would instead suggest

Likes.objects.filter(post=self).count()

Somebody else correct me if I’m wrong, but calling len() on a query result will force the ORM to download the entire data set and run the len() in python, but a .count() is part of the ORM and will put a COUNT into SQL, which will be much more efficient.

2 Likes