# articles/models.py
from django.db import models
from users.models import User
class Article(models.Model):
# 한 user가 여러 article. 1:many. FK
user = models.ForeignKey(User, on_delete=models.CASCADE) # 삭제할 때 없애준다
title = models.CharField(max_length=50)
content = models.TextField()
image = models.ImageField(blank=True, upload_to='%Y/%m/')
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
likes = models.ManyToManyField(User, related_name="like_articles") # 추가
def __str__(self):
return str(self.title)
ManyToMany를 쓸 때는 related_name
을 설정해주는 게 좋다.
위와 같이 설정하면 user.like_articles
로 '좋아요 개수' 구할 수 있다.
user.article_set
하면 user가 작성한 게시글이 표시된다.모델을 만들었으니 makemigrations, migrate 하면
admin에서 like 옵션이 생긴 것을 확인할 수 있다.
이제 urls와 views를 만든다.
# articles/urls.py
from django.urls import path
from articles import views
urlpatterns = [
path('', views.ArticleView.as_view(), name='article_view'),
path('<int:article_id>/', views.ArticleDetailView.as_view(), name='article_detail_view'),
path('<int:article_id>/comment/', views.CommentView.as_view(), name='comment_view'),
path('<int:article_id>/comment/<int:comment_id>', views.CommentDetailView.as_view(), name='comment_detail_view'),
path('<int:article_id>/like/', views.LikeView.as_view(), name='like_view'),
# articles/views.py
from rest_framework.generics import get_object_or_404
from rest_framework.views import APIView
from rest_framework import status, permissions
from rest_framework.response import Response
from articles.models import Article, Comment
from articles.serializers import ArticleSerializer, ArticleListSerializer, ArticleCreateSerializer, CommentSerializer, CommentCreateSerializer
# 토글 로직 (했으면 빼고, 안 했으면 넣고)
class LikeView(APIView):
def post(self, request, article_id):
article = get_object_or_404(Article, id=article_id) # 게시글 받아오기
# request 유저가 글 좋아요 한 사람들 중에 있다면 빼주기
if request.user in article.likes.all():
article.likes.remove(request.user) # models에 있는 클래스article의 likes
return Response("언팔로우 했습니다.", status=status.HTTP_200_OK)
else:
article.likes.add(request.user)
return Response("팔로우 했습니다.", status=status.HTTP_200_OK)