通过表格嵌套预取

时间:2019-04-23 12:01:28

标签: django django-orm

我正在尝试在客户查询集中预取按产品分组的订单行。是否可以使用Django ORM预取一个穿透表,还是应该以其他方式进行此操作?

class Customer(models.Model):
    ...

class Order(models.Model):
    customer = models.ForeignKey(Customer, related_name='%(class)s_customer')
    lines = models.ManyToManyField(
        Product,
        through='OrderLine'
        through_fields=('order', 'product')
    )
    ...

class OrderLine(model.Model):
    product = models.ForeignKey(Product, related_name='%(class)s_product')
    order = models.ForeignKey(Order, related_name='%(class)s_order')

由于customer不是OrderLine模型上的字段,因此以下操作无效

customers = Customer.objects.all().prefetch_related(
    Prefetch(
        'order_customer',
        queryset=OrderLine.objects.filter(**query),
        to_attr='order_lines'
        )
    )

1 个答案:

答案 0 :(得分:0)

您可以执行嵌套的预取操作,以获取相关的订单,并从那里获取相关的订单行:

customers = Customer.objects.prefetch_related(
    Prefetch(
        'order_customer',
        queryset=Order.objects.prefetch_related(Prefetch(
            'orderline_order',
            queryset=OrderLine.objects.filter(**query)
        ))
    )
)