본문 바로가기

SERVER/Django

[Django] 인스타그램 클론 코딩 Serializer 적용 및 API TEST하기

모델 선택 및 데이터 삽입

선택한 모델: Post 모델. (Post 모델과 1:N 관계를 갖는 Comment, Like, File 모델)

 

 


Serializer

  • Nested Serializer로 post와 post_likes, comments, post_files 관계 표현.
  • Serializer method field로 author(User 모델)의 field인 nickname을 가져와 사용.
class PostSerializer(serializers.ModelSerializer):
    author_name = serializers.SerializerMethodField()
    likes_count = serializers.SerializerMethodField()
    comments_count = serializers.SerializerMethodField()
    post_likes = LikeSerializer(many=True, read_only=True)   # read_only: 요청 파라미터에 포함되지 않음.
    comments = CommentSerializer(many=True, read_only=True)
    post_files = FileSerializer(many=True, read_only=True)

    class Meta:
        model = Post
        fields = ['author_name', 'author', 'content', 'created_date', 'updated_date', 'comments_count', 'likes_count', 'post_likes', 'comments', 'post_files']

    def get_author_name(self, obj):
        return obj.author.nickname

    def get_comments_count(self, obj):
        return obj.comments.count()

    def get_likes_count(self, obj):
        return obj.post_likes.count()

 

- 추가 User serializer

 

class UserSerializer(serializers.ModelSerializer):
    profile = ProfileSerializer(required=True)
    posts = PostSerializer(many=True, read_only=True)
    # comments = CommentSerializer(many=True, read_only=True)
    followers = FollowSerializer(many=True, read_only=True)
    followings = FollowSerializer(many=True, read_only=True)
    # likes = LikeSerializer(many=True, read_only=True)

    posts_count = serializers.SerializerMethodField()
    followers_count = serializers.SerializerMethodField()
    followings_count = serializers.SerializerMethodField()

    class Meta:
        model = User
        fields = ['nickname', 'username', 'password', 'email', 'profile', 'followers_count', 'followings_count', 'posts_count', 'posts', 'followers', 'followings']

    def create(self, validated_data):
        profile_data = validated_data.pop('profile')
        user = User.objects.create(**validated_data)
        Profile.objects.create(user=user, **profile_data)
        return user

    def get_posts_count(self, obj):
        return obj.posts.count()

    def get_followers_count(self, obj):
        return obj.followers.count()

    def get_followings_count(self, obj):
        return obj.followings.count()

모든 데이터를 가져오는 API 만들기

  • URL: api/posts/
  • METHOD: GET
  • POSTMAN에서 TEST (serializer 수정 전 결과)

Response

[
    {
        "author_name": "user3",
        "author": 3,
        "content": "그림 그리는 중~",
        "created_date": "2021-10-05T19:51:55.927811+09:00",
        "updated_date": "2021-10-05T19:51:55.927811+09:00",
        "post_likes": [
            {
                "id": 1,
                "created_date": "2021-10-11T14:26:53.791390+09:00",
                "updated_date": "2021-10-11T14:26:53.972385+09:00",
                "user": 1,
                "post": 1
            },
            {
                "id": 2,
                "created_date": "2021-10-11T14:26:53.791390+09:00",
                "updated_date": "2021-10-11T14:26:53.972385+09:00",
                "user": 2,
                "post": 1
            },
            {
                "id": 4,
                "created_date": "2021-10-11T14:26:53.791390+09:00",
                "updated_date": "2021-10-11T14:26:53.972385+09:00",
                "user": 3,
                "post": 1
            }
        ],
        "comments": [],
        "post_files": []
    },
    {
        "author_name": "user1",
        "author": 1,
        "content": "시험 일주일 전~",
        "created_date": "2021-10-05T19:52:16.109273+09:00",
        "updated_date": "2021-10-05T19:52:16.109273+09:00",
        "post_likes": [
            {
                "id": 3,
                "created_date": "2021-10-11T14:26:53.791390+09:00",
                "updated_date": "2021-10-11T14:26:53.972385+09:00",
                "user": 1,
                "post": 2
            },
            {
                "id": 5,
                "created_date": "2021-10-11T14:26:53.791390+09:00",
                "updated_date": "2021-10-11T14:26:53.972385+09:00",
                "user": 2,
                "post": 2
            }
        ],
        "comments": [],
        "post_files": []
    },
    {
        "author_name": "user2",
        "author": 2,
        "content": "노래 듣는 중~",
        "created_date": "2021-10-05T19:52:33.103979+09:00",
        "updated_date": "2021-10-05T19:52:33.103979+09:00",
        "post_likes": [
            {
                "id": 6,
                "created_date": "2021-10-11T14:26:53.791390+09:00",
                "updated_date": "2021-10-11T14:26:53.972385+09:00",
                "user": 3,
                "post": 3
            }
        ],
        "comments": [],
        "post_files": []
    },
    {
        "author_name": "user2",
        "author": 2,
        "content": "나는 휴학생~",
        "created_date": "2021-10-05T19:52:52.716996+09:00",
        "updated_date": "2021-10-05T19:52:52.716996+09:00",
        "post_likes": [],
        "comments": [],
        "post_files": []
    },
    {
        "author_name": "user3",
        "author": 3,
        "content": "실습 나가는 길~",
        "created_date": "2021-10-05T19:53:08.781585+09:00",
        "updated_date": "2021-10-05T19:53:08.781585+09:00",
        "post_likes": [],
        "comments": [
            {
                "author_name": "user1",
                "author": 1,
                "post": 5,
                "content": "헐 벌써?",
                "created_date": "2021-10-05T19:55:05.360616+09:00"
            },
            {
                "author_name": "user2",
                "author": 2,
                "post": 5,
                "content": "오마이갓",
                "created_date": "2021-10-05T19:56:16.509982+09:00"
            },
            {
                "author_name": "user3",
                "author": 3,
                "post": 5,
                "content": "시간 빠르다~",
                "created_date": "2021-10-05T19:57:03.714520+09:00"
            }
        ],
        "post_files": []
    },
    {
        "author_name": "user1",
        "author": 1,
        "content": "drfdrfdrf",
        "created_date": "2021-10-11T16:19:28.760878+09:00",
        "updated_date": "2021-10-11T16:19:28.760878+09:00",
        "post_likes": [],
        "comments": [],
        "post_files": []
    },
    {
        "author_name": "user1",
        "author": 1,
        "content": "시험기간이야~~",
        "created_date": "2021-10-11T17:36:09.038490+09:00",
        "updated_date": "2021-10-11T17:36:09.038490+09:00",
        "post_likes": [],
        "comments": [],
        "post_files": []
    }
]

새로운 데이터를 Create하도록 요청하는 API 만들기

  • URL: api/posts/
  • Method: POST
  • Body:

{

    "author"2,

    "content""밖에 비가 와서 짜증나"

}

  • POSTMAN에서 TEST (serializer 수정 전 결과)

Response

{
    "author_name": "user2",
    "author": 2,
    "content": "밖에 비가 와서 짜증나",
    "created_date": "2021-10-11T22:30:20.357470+09:00",
    "updated_date": "2021-10-11T22:30:20.357470+09:00",
    "post_likes": [],
    "comments": [],
    "post_files": []
}