백엔드
Django에 대하여(34)_DRF with N:1 Relation - GET
데이터분석가 이채은
2024. 5. 22. 09:00
1. 사전 준비
1-1. Comment 모델 정의
Comment 클래스 정의 및 데이터 베이스 초기화
# articles/models.py
class Comment(models.Model):
artilce = models.ForeignKey(Article, on_delete=models.CASCADE
content = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
Migration 및 fixtures 데이터 로드
$ python manage.py makemigrations
$ python manage.py migrate
$ python manage.py loaddata articles.json comments.json
2. GET - List
댓글 목록 조회를 위한 CommentSerializer 정의
# articles/serializers.py
from .models import Article, Comment
class CommentSerializer(serializers.ModelSerializer):
class Meta:
model = Comment
fields = '__all__'
url 작성
urlpatterns = [
...,
path('comments/', views.comment_list),
]
view 함수 작성
# articles/viws.py
from .models import Article, Comment
from .serializers import ArticleListSerializer, ArticleSerializer, CommentSerializer
@api_view(['GET'])
def comment_list(request):
comments = Comment.objects.all()
serializer = CommentListSerializer(comments, many=True)
return Response(serializer.data)
3. GET - Detail
단일 댓글 조회를 위한 url 및 view 함수 작성
# articles/viws.py
@api_view(['GET'])
def comment_detail(request, comment_pk):
comments = Comment.objects.get(pk=comment_pk)
serializer = CommentSerializer(comment)
return Response(serializer.data)