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__"