How to retrieve all Variants of a single Product in a single JSON object per Product- Django Rest Framework
The way I am doing it is like in getProductList function in my views.py and it is giving me each product with its variants in different objects for eg the same product with different size is put into a different object even if the product is the same like so:
JSON:
[
{
"prod_id": {
"id": 3,
"prod_name": "CRUISER-149S-DEERCALF",
"category": 2
},
"size_id": {
"id": 2,
"name": "26"
},
"color_id": 2,
"image_id": {
"id": 10,
"prod_image": "/media/products/IMG_7617_ftgqoa.jpg"
}
},
{
"prod_id": {
"id": 3,
"prod_name": "CRUISER-149S-DEERCALF",
"category": 2
},
"size_id": {
"id": 3,
"name": "27"
},
"color_id": 2,
"image_id": {
"id": 10,
"prod_image": "/media/products/IMG_7617_ftgqoa.jpg"
}
}
]
Is there a way to maybe make it more optimized? like have only one product object that has all the info of a single product like size for example can be a property with values of all sizes in it like size: [26, 27] instead of a different object if a size is different.
models.py
class Products(models.Model):
prod_name = models.CharField(max_length=200)
category = models.ForeignKey(Categories,null=True, on_delete=models.SET_NULL)
def __str__(self):
return '%s'%(self.prod_name)
class Variants(models.Model):
prod_id = models.ForeignKey(Products, on_delete=models.CASCADE)
size_id = models.ForeignKey(Size, null=True, on_delete=models.SET_NULL, related_name='variants')
color_id = models.ForeignKey(Color, null=True, on_delete=models.SET_NULL, default='')
image_id = models.ForeignKey(Image,null=True, on_delete=models.SET_NULL, default='')
def __str__(self):
return '%s %s %s %s %s %s %s'%(self.id , self.prod_id, self.size_id, self.image_id, self.color_id, self.quantity, self.price)
serializer.py
class ProductsSerializer(serializers.ModelSerializer):
# variants = serializers.StringRelatedField(many=True)
class Meta:
model = Products
fields = "__all__"
class SizeSerializer(serializers.ModelSerializer):
class Meta:
model = Size
fields = "__all__"
class VariantsSerializer(serializers.ModelSerializer):
prod_id = ProductsSerializer(many=False, read_only=True)
image_id = ImageSerializer(many=False, read_only=True)
size_id = SizeSerializer(many=False, read_only=True)
class Meta:
model = Variants
fields = ['prod_id', 'size_id', 'quantity', 'price', 'color_id', 'image_id']
views.py
def getProductList(request):
print(request.GET.get('category'))
if(request.method == 'GET'):
if request.GET.get('category') == 'all' :
productList = Variants.objects.all().select_related()
serializer = VariantsSerializer(productList, many=True)
return JsonResponse(serializer.data, safe=False)
return JsonResponse({'details': 'Error in getting product list'})