我是使用ORM执行数据库调用的新手,我找不到优化代码/查询的好方法。
我有Productss可以在ProductGroups中。产品可以有0到n的价格。价格由其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
答案 0 :(得分:3)
您可以尝试aggregates-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')