Django

Relationship과 DRF(with. particular seed)

zhelddustmq 2024. 8. 29. 16:56

 

django-seed에서 앱이 아니라 특정 모델만 지정해서 댓글 만들기!

https://github.com/Brobin/django-seed

 

python manage.py seed articles --number=20 --seeder "Comment.article_id" 2

 

Comment 만들어보기

models.py

class Comment(models.Model):
    article = models.ForeignKey(
        Article, on_delete=models.CASCADE, related_name="comments")
    content = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

serializers.py

class CommentSerializer(serializers.ModelSerializer):
    class Meta:
        model = Comment
        fields = "__all__"
        read_only_fields = ("article",)  # article은 읽기 전용으로 부름

views.py

class CommentListAPIView(APIView):

    def get(self, request, article_pk):
        article = get_object_or_404(Article, pk=article_pk)
        comments = article.comments.all()
        serialier = CommentSerializer(comments, many=True)
        return Response(serialier.data)

    def post(self, request, article_pk):
        article = get_object_or_404(Article, pk=article_pk)
        serializer = CommentSerializer(data=request.data)
        if serializer.is_valid(raise_exception=True):
            serializer.save(article=article) # request.data에는 article에 대한 정보가 없어 article도 인자값으로 넘겨줘야함.
            # serializer.data를 빈{}로 보내도 됨
            return Response(serializer.data, status=status.HTTP_201_CREATED)


class CommentDetailAPIView(APIView):
    def get_object(self, comment_pk):
        return get_object_or_404(Comment, pk=comment_pk)

    def put(self, request, comment_pk):
        comment = self.get_object(comment_pk)
        serializer = CommentSerializer(
            comment, data=request.data, partial=True)
        if serializer.is_valid(raise_exception=True):
            serializer.save()
            return Response(serializer.data)

    def delete(self, request, comment_pk):
        comment = self.get_object(comment_pk)
        comment.delete()
        data = {"pk": f"{comment_pk} is deleted."}
        return Response(data, status=status.HTTP_204_NO_CONTENT)

urls.py

from django.urls import path
from . import views
urlpatterns = [
				.
                    		.
                    		.
    path("<int:article_pk>/comments/", views.CommentListAPIView.as_view()),
    path("comments/<int:comment_pk>/", views.CommentDetailAPIView.as_view()),
    				.
                    		.
                    		.
]

 

'Django' 카테고리의 다른 글

JSON Web Token, JWT  (0) 2024.08.30
Serializer 활용하기  (0) 2024.08.29
DRF CBV  (0) 2024.08.29
DRF와 Postman (GET, PUT, DELETE, POST)  (0) 2024.08.29
Django Seed(Response와 Serializer)  (0) 2024.08.29