我刚开始使用orm来执行数据库调用,但我很难找到优化代码/查询的好方法。
我有产品可以在产品组中。产品可以有0到n的价格。价格是由其作用位置和价值决定的。
我想显示产品组中所有产品的最低和最高价格。
我写的代码正在工作,但是由于数据库访问量太大,速度非常慢。如有任何帮助,我们将不胜感激:)
模型:

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

最佳答案

您可以尝试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')

07-24 09:45
查看更多