[英]Reduce the execution time of django view
我有一個 django 視圖,它返回產品 model 的所有產品。 情況是折扣取決於產品和用戶,因此必須在每次運行時計算。 我只添加了 3500 個產品,服務器需要 40-50 秒才能響應。 我想知道添加 100,000 個產品需要多長時間。 我該如何優化呢?
def apply_discount(product_obj,user_obj):
discount1 = product_obj.brand.discount
try:
discount2 = user_obj.special_discount.all().filter(brand=product_obj.brand.name)[0].discount
except IndexError:
discount2 = 0
total_discount = discount1 + discount2
discount_apply_on = product_obj.brand.discount_on
price= getattr(product_obj, discount_apply_on)
final= round(price - (price*total_discount)/100.00,3)
return (product_obj,price,final,total_discount)
@login_required
def product_list(request):
context = {}
product_qs = Product.objects.all()
product_list = []
for product in product_qs:
discount_applied_product = apply_discount(product,request.user)
product_list.append(discount_applied_product)
context['products'] = product_list
return render(request,"myapp/products.html",context)
模型.py
class BrandDiscount(models.Model):
name = models.CharField(max_length=255)
discount_on = models.CharField(max_length=25,default="retail_price")
discount = models.FloatField(default=0)
def __str__(self):
return self.name
class Product(models.Model):
brand = models.ForeignKey(BrandDiscount,on_delete=models.SET_NULL, null=True)
part_number = models.CharField(max_length=255)
description = models.TextField(null=True)
pack_price = models.FloatField(null=True)
units_per_pack = models.IntegerField(null=True)
single_price = models.FloatField(null=True)
retail_price = models.FloatField(null=True)
map_price = models.FloatField(null=True)
jobber_price = models.FloatField(null=True)
upc = models.CharField(max_length=255)
stock = models.IntegerField(default=0)
created_at = models.DateTimeField(auto_now_add=True)
app.yaml
runtime: python37
entrypoint: gunicorn -b :$PORT myProject.wsgi --timeout 120
instance_class: F4
handlers:
- url: /static
static_dir: static/
- url: /.*
secure: always
redirect_http_response_code: 301
script: auto
我已經在 Google App 引擎標准上部署了網站。 如果我增加 gunicorn 工人,會有幫助嗎?
嘗試對響應進行分頁。 我認為那將是你最好的選擇。
在您的本地環境中,您會在 3 秒內收到包含 400 個元素的響應
如果你做數學
(400 items / 3s) = ~ 133 items/s
(4500 items / 133 items/s) = ~ 33.83s
這種性能與您在 App Engine 中獲得的性能非常相似,正如另一個答案中提到的那樣,您可以對結果進行分頁。
But also you could send a JSON object with the information of all the elements to the interface and let a JavaScript function draw the elements (instead use render
to draw all your page) as the user needs them.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.