# views.py
class PostRetrieveListAPIView(RetrieveAPIView):
queryset = Post.objects.all()
serializer_class = PostRetrieveSerializer
# serializers.py
class PostRetrieveSerializer(serializers.ModelSerializer):
class Meta:
model = Post
exclude = ['create_dt'] # 'create_dt' 외 모든 데이터 전송
# serializers.py
class PostSerializerSub(serializers.ModelSerializer):
class Meta:
model = Post
fields = ['id', 'title']
class CommentSerializerSub(serializers.ModelSerializer):
class Meta:
model = Comment
fields = ['id', 'content', 'update_dt']
class PostSerializerDetail(serializers.Serializer):
post = PostRetrieveSerializer()
prevPost = PostSerializerSub()
nextPost = PostSerializerSub()
commentList = CommentSerializerSub(many=True)
# views.py
def get_prev_next(instance):
try:
prev = instance.get_previous_by_update_dt() # Django 기본 메서드
except instance.DoesNotExist:
prev = None
try:
next_ = instance.get_next_by_update_dt() # Django 기본 메서드
except instance.DoesNotExist:
next_ = None
return prev, next_
class PostRetrieveListAPIView(RetrieveAPIView):
queryset = Post.objects.all()
serializer_class = PostSerializerDetail
def retrieve(self, request, *args, **kwargs):
instance = self.get_object()
prevInstance, nextInstance = get_prev_next(instance)
commentList = instance.comment_set.all()
data = {
'post': instance,
'prevPost': prevInstance,
'nextPost': nextInstance,
'commentList' : commentList,
}
serializer = self.get_serializer(instance = data)
return Response(serializer.data)
PostRetrieveListAPIView
RetrieveAPIView
>RetrieveModelMixin
참고.class RetrieveModelMixin: """ Retrieve a model instance. """ def retrieve(self, request, *args, **kwargs): instance = self.get_object() serializer = self.get_serializer(instance) return Response(serializer.data)
get_previous_by_update_dt(), get_next_by_update_dt()
두 메서드를 사용할 때는 exception 처리를 해야하기 때문에 별도로
get_prev_next
함수를 만들었다. 공식문서 참고.