좋아요 수를 likes
필드로 저장한다.
→ ManyToMany 필드
send할 때마다 좋아요 버튼 클릭한 것처럼 바뀜
#users/urls.py
path('follow/<int:id>/', views.FollowView.as_view(), name='follow_view')
#users/model.py
following = models.ManyToManyField('self', symmetrical=False, related_name='followers')
#users/views.py
class FollowView(APIView):
def post(self, request, id):
you = get_object_or_404(User, id=id)
me = request.user
if me in you.followers.all():
you.followers.remove(me)
return Response({"message": "언팔로우 성공"}, status=status.HTTP_200_OK)
else:
you.followers.add(me)
return Response({"message": "팔로우 성공"}, status=status.HTTP_200_OK)
좋아요 한 사람, 댓글 확인
{
"article_id": 8,
"user": "testuser3",
"likes": [
"testuser3"
],
"comment_set": [
{
"id": 1,
"content": "댓글 수정 1",
"created_at": "2024-08-15T23:46:50.171496+09:00",
"updated_at": "2024-08-15T23:48:39.490927+09:00",
"user": 4
}
],
"content": "토큰 발급 성공 후 수정한 게시물",
"image": null,
"created_at": "2024-08-15T19:24:34.219196+09:00",
"updated_at": "2024-08-15T23:46:42.040382+09:00"
}
좋아요 개수 출력
{
"article_id": 8,
"user": "testuser3",
"likes": [
"testuser3"
],
"likes_count": 1,
"comment_set": [
{
"id": 1,
"content": "댓글 수정 1",
"created_at": "2024-08-15T23:46:50.171496+09:00",
"updated_at": "2024-08-15T23:48:39.490927+09:00",
"user": 4
}
],
"content": "토큰 발급 성공 후 수정한 게시물",
"image": null,
"created_at": "2024-08-15T19:24:34.219196+09:00",
"updated_at": "2024-08-15T23:46:42.040382+09:00"
}
class ArticleSerializer(serializers.ModelSerializer):
user = serializers.SerializerMethodField()
likes = serializers.StringRelatedField(many=True)
likes_count = serializers.SerializerMethodField()
def get_likes_count(self, obj):
return obj.likes.count()
def get_user(self, obj):
return obj.user.username
comment_set = CommentSerializer(many=True)
class Meta:
model = Article
fields = '__all__'
모델에서 정의된 related_name
을 사용해서 가져와야 한다. 안그러면 AttributeError 발생