Remove color in post model, optimize queryset

This commit is contained in:
jhyns 2023-05-18 11:02:46 +09:00
parent ba4f4db462
commit ffbb40e7d9
4 changed files with 28 additions and 28 deletions

View File

@ -13,7 +13,6 @@ admin.site.register(Image)
class PostAdmin(admin.ModelAdmin):
list_display = (
"product",
"color",
"storage",
"price",
"text",

View File

@ -43,7 +43,6 @@ class Post(models.Model):
product = models.ForeignKey(
Product, on_delete=models.CASCADE, related_name="posts"
)
color = models.CharField(max_length=20)
storage = models.ForeignKey(ProductStorage, on_delete=models.CASCADE)
price = models.IntegerField()
text = models.TextField()

View File

@ -4,38 +4,38 @@ from rest_framework.serializers import ModelSerializer
from market.models import (
Brand,
Product,
ProductStorage,
Post,
Image,
)
class BrandSerializer(ModelSerializer):
class Meta:
model = Brand
fields = "__all__"
class ProductStorageSerializer(ModelSerializer):
class Meta:
model = ProductStorage
fields = ("storage",)
class ProductSerializer(ModelSerializer):
storage = ProductStorageSerializer(many=True, read_only=True)
storage = serializers.StringRelatedField(many=True)
class Meta:
model = Product
fields = ("id", "name", "brand", "storage")
depth = 1
class ProductListSerializer(ModelSerializer):
brand = serializers.CharField(source="brand.name")
class Meta:
model = Product
fields = ("id", "name", "brand")
fields = ("id", "name")
class BrandSerializer(ModelSerializer):
products = ProductListSerializer(many=True, read_only=True)
class Meta:
model = Brand
fields = ["id", "name", "products"]
class BrandListSerializer(ModelSerializer):
class Meta:
model = Brand
fields = "__all__"
class ImageSerializer(ModelSerializer):
@ -48,15 +48,14 @@ class PostSerializer(ModelSerializer):
product = ProductListSerializer(read_only=True)
nickname = serializers.CharField(source="author.nickname")
images = ImageSerializer(many=True, read_only=True)
# storage = serializers.CharField(source="storage.storage")
storage = serializers.CharField(source="storage.storage")
class Meta:
model = Post
fields = (
"id",
"product",
"color",
"storage__storage",
"storage",
"price",
"text",
"nickname",

View File

@ -30,7 +30,11 @@ class BrandViewset(ActionBasedMixin, ModelViewSet):
class ProductViewset(ActionBasedMixin, ModelViewSet):
queryset = Product.objects.all()
queryset = (
Product.objects.all()
.select_related("brand")
.prefetch_related("storage")
)
serializer_class = ProductSerializer
serializer_class_map = {
"posts": PostSerializer,
@ -52,11 +56,10 @@ class ProductViewset(ActionBasedMixin, ModelViewSet):
class PostViewset(ActionBasedMixin, ModelViewSet):
queryset = Post.objects.all().select_related(
"storage",
"product",
"author",
"product__brand",
queryset = (
Post.objects.all()
.select_related("storage", "product", "author", "product__brand")
.prefetch_related("images")
)
serializer_class = PostSerializer
permission_classes = [IsAuthenticated, IsAuthorOrReadOnly]