我刚开始使用ORM来执行我的数据库调用,我很难找到一种优化代码/查询的好方法。
我有产品可以在ProductGroups。产品可以有0到n的价格。A价格是由其ActorLocation及其值定义的。我想显示ProductGroup中所有产品的最低和最高价格。
我编写的代码正在工作,但由于数据库访问的数量很大,所以速度非常慢。如有任何帮助,我们将不胜感激:)
模型:
class ProductGroup(OwnedClass):
name = models.CharField(max_length=200, blank=False)
class Product(models.Model):
name = models.CharField(max_length=200, blank=True)
internal_code = models.CharField(max_length=200, blank=True)
description = models.CharField(max_length=1000, blank=True)
product_group = models.ForeignKey(
ProductGroup, blank=True, null=True, on_delete=models.CASCADE)
class Price(models.Model):
price_without_taxes = models.FloatField(default=None, null=True)
location = models.ForeignKey(
ActorLocation, blank=True, null=True, on_delete=models.CASCADE)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
class ActorLocation(models.Model):
name = models.CharField(max_length=200, blank=False, null=False)下面是我的函数,用于生成发送到我的ProductGroupSerializer的上下文:
def get_context(product_groups):
locations = company.actor_locations.all()
for product_group in product_groups:
price_list = []
products = product_group.product_set.all()
for product in products:
for location in locations:
price = Price.objects.filter(product=product, location=location).last()
if price:
price_list.append(price.price_without_taxes)
if price_list:
context = {'lowest_product_price': round(min(price_list), 2), 'highest_product_price': round(max(price_list), 2)}
else:
context = {'lowest_product_price': "", 'highest_product_price': ""}
contexts[product_group.id] = context
return contexts发布于 2018-05-14 07:43:23
您可以尝试集合-over a-queryset,例如:
from django.db.models import Max, Min
locations = company.actor_locations.all()
Price.objects.annotate(
lowest_product_price=Min(price_without_taxes),
highest_product_price=Max(price_without_taxes)
).filter(
product__product_group__in=product_groups,
location__in=locations
).values(
'lowest_product_price', 'highest_product_price')https://stackoverflow.com/questions/50324819
复制相似问题