Add PostListSerializer

This commit is contained in:
jhyns 2023-06-16 16:36:27 +09:00
parent ee12a15b5e
commit 7700664f81
3 changed files with 36 additions and 2 deletions

View File

@ -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}"

View File

@ -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")

View File

@ -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],