问题
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
回答1:
I assumed you have the Replies
model like this:
class Replies(models.Model):
comment = Models.Foreignkey(Comment)
content = models.CharField(max_length=1000,blank=True)
likes = models.IntegerField(default=0)
Then you could use rest_framework.serializers.ModelSerializer
class (http://www.django-rest-framework.org/api-guide/serializers/#modelserializer):
from rest_framework import serializers
class RepliesSerializer(serializers.ModelSerializer):
class Meta:
model = Replies
fields = ('id', 'content', 'parent_id', 'likes')
parent_id = serializers.Field(source='comment.parent_id')
class CommentSerializer(serializers.ModelSerializer):
class Meta:
model = Comment
fields = ('id', 'parent_id', 'content', 'likes', 'replies')
replies = RepliesSerializer(many=True)
来源:https://stackoverflow.com/questions/29591287/django-rest-framework-nested-object-response