减少django视图的执行时间

问题描述 投票:0回答:2

我有一个django视图,它返回Product模型的所有产品。情况是折扣取决于产品以及用户,因此必须在每次运行时进行计算。我仅添加了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)

models.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引擎标准上部署了网站。如果我增加黑帮员工,会有所帮助吗?

python django gunicorn
2个回答
2
投票

尝试对响应进行分页。我认为那将是您最好的选择。

https://docs.djangoproject.com/en/3.0/topics/pagination/


1
投票

在您的本地环境中,您会在3秒内收到包含400个元素的回复

如果你做数学

(400 items / 3s) = ~ 133 items/s
(4500 items / 133 items/s) = ~ 33.83s

此性能与您在App Engine中获得的性能非常相似,如另一个答案中所述,您可以对结果进行分页。

但是您也可以根据需要将包含所有元素信息的JSON对象发送到接口,并让JavaScript函数根据用户需要来绘制元素(而不是使用render来绘制所有页面。

© www.soinside.com 2019 - 2024. All rights reserved.