# postings/models
class Comment(TimeStampedModel):
comment = models.CharField(max_length=300)
user = models.ForeignKey('users.User', related_name='comments', on_delete=models.PROTECT)
post = models.ForeignKey('Post', related_name='comments', on_delete=models.CASCADE)
class Meta:
db_table = "comments"
# postings/urls
from django.urls import path
from .views import PostingView, CommentView
urlpatterns = [
path("upload", PostingView.as_view()),
path("comment", CommentView.as_view()),
]
import json, jwt
from django.views import View
from django.http import JsonResponse
from users.models import User
from .models import Post, Comment
from secret import ALGORITHM
from config.settings import SECRET_KEY
class CommentView(View):
def post(self, request):
try:
data = json.loads(request.body)
comment = data['comment']
post_id = data['post_id']
payload = jwt.decode(data["token"], SECRET_KEY, ALGORITHM)
user_id = payload['user_id']
if not User.objects.filter(id = user_id).exists():
return JsonResponse({'MESSAGE': "User Does Not Exist"}, status=404)
if not Post.objects.filter(id = post_id).exists():
return JsonResponse({'MESSAGE': "Posting Does Not Exist"}, status=404)
Comment.objects.create(
comment = comment,
user_id = payload['user_id'],
post_id = post_id,
)
return JsonResponse({"MESSAGE": "Post created!"}, status=201)
except KeyError:
return JsonResponse({"MESSAGE": "KEY_ERROR"}, status=400)
comment를 하기 위해서는 토큰으로 인증된 유저, 포스트id, comment가 필요합니다.
만약 User db에 있는 id가 유저로부터 입력받은 user_id와 비교해 존재하지 않는다면(다르다면) 유저가 존재하지 않는다는 메시지를 던져줍니다. 그리고 Post의 id와 입력받은 post_id와 비교해 존재하지 않는다면(다르다면) 포스팅이 존재하지 않는다는 메시지를 던져줍니다. 여기서 user = User.objects.all()로 지정해 user.id로 변경할 수 있습니다.
class CommentView(View):
.
.
.
def get(self, request):
comments = Comment.objects.all()
results = []
for comment in comments:
results.append(
{
"comment" : comment.comment,
"post_id" : comment.post_id,
"user_id" : comment.user_id,
"post" : {
"post_title" : comment.post.post_title,
"post_content" : comment.post.post_content,
}
}
)
return JsonResponse({"postings" : results}, status = 200)
Comment의 항목들을 comments에 저장 후 for문을 돌려 하나씩 정보들을 저장합니다.
user_id와 user.id간의 관계
view
결과(with postman)