2023-05-03 14:23:44 +09:00
|
|
|
from rest_framework.decorators import action
|
2023-05-17 17:13:47 +09:00
|
|
|
from rest_framework.permissions import AllowAny, IsAuthenticated
|
2023-05-03 14:23:44 +09:00
|
|
|
from rest_framework.response import Response
|
|
|
|
from rest_framework.viewsets import ModelViewSet
|
|
|
|
|
|
|
|
from core.mixins import ActionBasedMixin
|
2023-05-17 16:10:25 +09:00
|
|
|
from core.permissions import IsAuthorOrReadOnly, IsAdminUserOrReadOnly
|
2023-05-03 14:23:44 +09:00
|
|
|
from market.models import Brand, Product, Post
|
|
|
|
from market.serializers import (
|
|
|
|
BrandSerializer,
|
|
|
|
ProductSerializer,
|
|
|
|
PostSerializer,
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
class BrandViewset(ActionBasedMixin, ModelViewSet):
|
|
|
|
queryset = Brand.objects.all()
|
|
|
|
serializer_class = BrandSerializer
|
2023-05-17 16:10:25 +09:00
|
|
|
permission_classes = [IsAdminUserOrReadOnly]
|
2023-05-16 21:49:52 +09:00
|
|
|
pagination_class = None
|
2023-05-03 14:23:44 +09:00
|
|
|
|
|
|
|
|
|
|
|
class ProductViewset(ActionBasedMixin, ModelViewSet):
|
2023-05-18 11:02:46 +09:00
|
|
|
queryset = (
|
|
|
|
Product.objects.all()
|
|
|
|
.select_related("brand")
|
|
|
|
.prefetch_related("storage")
|
|
|
|
)
|
2023-05-03 14:23:44 +09:00
|
|
|
serializer_class = ProductSerializer
|
|
|
|
serializer_class_map = {
|
|
|
|
"posts": PostSerializer,
|
|
|
|
}
|
2023-05-17 16:10:25 +09:00
|
|
|
permission_classes = [IsAdminUserOrReadOnly]
|
2023-05-03 14:23:44 +09:00
|
|
|
|
|
|
|
@action(detail=True, methods=["GET"])
|
|
|
|
def posts(self, request, pk):
|
|
|
|
product = self.get_object()
|
|
|
|
queryset = product.posts.all()
|
|
|
|
|
|
|
|
page = self.paginate_queryset(queryset)
|
|
|
|
if page is not None:
|
|
|
|
serializer = self.get_serializer(page, many=True)
|
|
|
|
return self.get_paginated_response(serializer.data)
|
|
|
|
|
|
|
|
serializer = self.get_serializer(queryset, many=True)
|
|
|
|
return Response(serializer.data)
|
|
|
|
|
|
|
|
|
|
|
|
class PostViewset(ActionBasedMixin, ModelViewSet):
|
2023-05-18 11:02:46 +09:00
|
|
|
queryset = (
|
|
|
|
Post.objects.all()
|
|
|
|
.select_related("storage", "product", "author", "product__brand")
|
|
|
|
.prefetch_related("images")
|
2023-05-17 17:13:47 +09:00
|
|
|
)
|
2023-05-03 14:23:44 +09:00
|
|
|
serializer_class = PostSerializer
|
|
|
|
permission_classes = [IsAuthenticated, IsAuthorOrReadOnly]
|
|
|
|
permission_classes_map = {
|
|
|
|
"list": [AllowAny],
|
|
|
|
"retrieve": [AllowAny],
|
|
|
|
}
|
|
|
|
|
|
|
|
def perform_create(self, serializer):
|
|
|
|
serializer.save(author=self.request.user)
|