Djangoroidの奮闘記

python,django,angularJS1~三十路過ぎたプログラマーの奮闘記

Django REST Frameworkに再挑戦 その12 Comments in Post Detail API View

概要

Django REST Frameworkに再挑戦 その12 Comments in Post Detail API View

参考サイト

www.django-rest-framework.org

www.codingforentrepreneurs.com

Comments in Post Detail API View

  • post/api/serializers.py にコードを追記する。
from comments.api.serializers import CommentSerializer
from comments.models import Comment
...
class PostDetailSerializer(ModelSerializer):
...
    comments = SerializerMethodField()
    class Meta:
        model = Post
        fields = [
            'url',
            'user',
            'id',
            'title',
            'slug',
            'content',
            'markdown',
            'publish',
            'image',
            'comments'#追加
        ]


    def get_comments(self, obj):
        content_type = obj.get_content_type
        object_id = obj.id
        c_qs = Comment.objects.filter_by_instance(obj) # def filter_by_instance(self, instance):のため、instance=objになる。
        comments = CommentSerializer(c_qs, many=True).data
        return comments

# 疑問、content_type, object_id ってなくてもよくね?
  • と思ったら、最後に、content_type, object_idは削除した!