i have 5 models below:
class Products:
product_name=models.CharField(max_length=300,blank=True)
product_price=models.IntegerField(blank=True)
class ProductImages(models.Model):
image=models.ImageField(upload_to='product_images',null=True,blank=True)
image_product=models.ForeignKey(Product,on_delete=models.CASCADE)
class ProductModel(models.Model):
model_product=models.ForeignKey(Product,null=True,on_delete=models.CASCADE)
model_name=models.CharField(max_length=130,blank=True)
class Colour(models.Model):
colour_name=models.CharField(max_length=20,blank=True)
colour_product=models.ForeignKey(Product,on_delete=models.CASCADE)
class Sale:
name=models.CharField(max_length=30,null=True,blank=True)
class ProductSale:
saleid=models.ForeignKey(Sale,on_delete=models.CASCADE)
product=models.ForeignKey(Product,on_delete=models.CASCADE)
I am filtering and getting products present in ProductSale on the basis of sale id
prod=ProductSale.objects.filter(sale=sale.id).prefetch_related('product')
Now i have product ids, but i want additional details also that is product images,colour,Model which is present in ProductImages model,Colour model,ProductModel model.How can i achieve this in most optimize way below is my try but its taking time and not optimized.
prod=ProductSale.objects.filter(sale=sale.id).prefetch_related('product')
for prod in prod:
pm=ProductModel.objects.filter(model_product=prod.product_id).values()
pc=Colour.objects.filter(colour_product=prod.product_id).values()
images=prod.product.productimages_set.all().order_by('id')[:2].values()
sale_product.append({
"product_id": prod.product.id,
"product_name": prod.product.product_name,
"stock": prod.product.product_quantity,
"product_price": prod.product.product_price,
"sale_price": prod.product.sale_price,
"saleprice_startdate": prod.product.saleprice_startdate,
"saleprice_enddate": prod.product.saleprice_enddate,
"product_category": prod.product.category_name,
"product_reviews": review_product,
"review_count": len(pr),
"product_images": images,
"product_colour": pc,
"product_model": pm,
})
How can i optimize the query get the data in a format which i am using in a dictionary, Kindly help badly stuck in this.