From 7700664f811764b258634becddcf27419f67407d Mon Sep 17 00:00:00 2001 From: jhyns Date: Fri, 16 Jun 2023 16:36:27 +0900 Subject: [PATCH] Add PostListSerializer --- market/models.py | 7 +++++-- market/serializers.py | 27 +++++++++++++++++++++++++++ market/viewsets.py | 4 ++++ 3 files changed, 36 insertions(+), 2 deletions(-) diff --git a/market/models.py b/market/models.py index 2652638..e846158 100644 --- a/market/models.py +++ b/market/models.py @@ -56,7 +56,7 @@ class Post(models.Model): ordering = ["-written_at"] def __str__(self): - return self.product.name + return f"{self.product} : {self.author} : {self.written_at}" class Image(models.Model): @@ -65,5 +65,8 @@ class Image(models.Model): ) image = models.ImageField(upload_to="images", blank=True, null=True) + class Meta: + ordering = ["-pk"] + def __str__(self): - return self.post.product.name + return f"{self.post}" diff --git a/market/serializers.py b/market/serializers.py index 3ef21da..659ef78 100644 --- a/market/serializers.py +++ b/market/serializers.py @@ -44,6 +44,33 @@ class ImageSerializer(ModelSerializer): fields = ("image",) +class PostListSerializer(ModelSerializer): + product = ProductListSerializer(read_only=True) + nickname = serializers.CharField(source="author.nickname") + image = serializers.SerializerMethodField() + storage = serializers.CharField(source="storage.storage") + + class Meta: + model = Post + fields = ( + "id", + "product", + "storage", + "price", + "text", + "nickname", + "status", + "written_at", + "image", + ) + + def get_image(self, obj): + first_image = obj.images.first() + return ImageSerializer( + instance=first_image, context=self.context + ).data["image"] + + class PostSerializer(ModelSerializer): product = ProductListSerializer(read_only=True) nickname = serializers.CharField(source="author.nickname") diff --git a/market/viewsets.py b/market/viewsets.py index 740465c..07d37a3 100644 --- a/market/viewsets.py +++ b/market/viewsets.py @@ -10,6 +10,7 @@ from market.serializers import ( BrandSerializer, ProductSerializer, PostSerializer, + PostListSerializer, ) @@ -53,6 +54,9 @@ class PostViewset(ActionBasedMixin, ModelViewSet): .prefetch_related("images") ) serializer_class = PostSerializer + serializer_class_map = { + "list": PostListSerializer, + } permission_classes = [IsAuthenticated, IsAuthorOrReadOnly] permission_classes_map = { "list": [AllowAny],