from django.db import models
from users.models import User
class TimeStampModel(models.Model):
created_at = models.DateTimeField(auto_now_add = True)
updated_at = models.DateTimeField(auto_now = True)
class Meta:
abstract = True
class Comment(TimeStampModel):
user = models.ForeignKey('users.User', on_delete=models.CASCADE)
post = models.ForeignKey('Post', on_delete=models.CASCADE)
comment = models.TextField(max_length=300)
class Meta:
db_table = 'comments'
TimeStampModel
상속 // 관련 블로그 정리글
모델 작성 완료 후 makemigartions, migrate 진행
class CommentView(View):
@signin_decorator
def post(self, request, post_id): ### *args 값 지정
try:
data = json.loads(request.body)
user = request.user
post = Post.objects.get(id = post_id)
Comment.objects.create(
comment = data['comment'],
user = user,
post = post,
)
return JsonResponse({'message' : 'SUCCESS'}, status = 200)
except KeyError:
return JsonResponse({"message": 'KEY_ERROR'}, status=400)
@signin_decorator
def get(self, request, post_id):
comment_list = [{
'id' : User.objects.get(id= comment.user.id).id,
'email' : User.objects.get(id= comment.user.id).email,
'username' : User.objects.get(id= comment.user.id).name,
'comment' : comment.comment,
'created_at': comment.created_at,
} for comment in Comment.objects.filter(post_id = post_id)
]
return JsonResponse({'RESULT' : comment_list}, status=200)
postings/urls.py
from django.urls import path
from postings.views import PostView, CommentView
urlpatterns = [
path('/post', PostView.as_view()),
path('/comment/<int:post_id>', CommentView.as_view())
]