I am new to Django Rest Framework, I am trying to implement Comment System API, I have model like this
class Comment(models.Model):
parent_id = models.IntegerField()
user = models.ForeignKey(User)
content = models.CharField(max_length=1000,blank=True)
likes = models.IntegerField(default=0)
active = models.BooleanField(default=True)
created = models.DateTimeField(auto_now=False,auto_now_add=True)
updated = models.DateTimeField(auto_now=True,auto_now_add=False)
where parent_id is used for replies, if Parent_id is greater than 0 that means current comment is reply to some other comment. Now I want to use Django Rest Framework to have json response like this :
[ { "id": 10, "parent_id": 0, "content": "Test Comment", "likes": 1, replies : [ { "id": 11, "parent_id": 10, "content": " Reply 1 Test Comment", "likes": 1, } { "id": 12, "parent_id": 10, "content": " Reply 2 Test Comment", "likes": 1, } ]
Can some buddy help me how to make such response ? I am using Django 1.7.6 and Django Rest Framework 3.1.1
I assumed you have the
Replies
model like this:Then you could use
rest_framework.serializers.ModelSerializer
class (http://www.django-rest-framework.org/api-guide/serializers/#modelserializer):