使用多级反向查找来预取对象 [英] Prefetch object with multiple levels of reverse lookups

查看:157
本文介绍了使用多级反向查找来预取对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Django 1.7中,并且使用了新的 Prefetch 对象,这是一个很好的补充。但是当我需要遍历多个关系时,我似乎被困住了。以下是我的代码:

I'm on Django 1.7 and have been using the new Prefetch objects which are a great addition. However I seem to be stuck when I need to traverse back more than one relationship. Here is my code:

    product_types = self.get_queryset().select_related().prefetch_related(
        'excise_category__exciseitem_set__unit',
        Prefetch(
            'bevtank_set__package_set__checkout_set',
            queryset=CheckOut.objects.filter(
                create_date__lte=end_date,
                submission__isnull=True,
                exempt=False),
            to_attr='checkouts_due'
        )
    )
    ...
    for pt in product_types:
        ...
        co = pt.checkouts_due
        ...

这给了我一个 ProductType'对象在 co = pt.checkouts_due 上没有属性'checkouts_due'。如果我将查找减少到单个反向查找(为了调试目的),它可以正常工作。

This gives me a 'ProductType' object has no attribute 'checkouts_due' on co = pt.checkouts_due. If I reduce the lookup to a single reverse lookup (for debug purposes) it works okay.

所以我的代码有问题,还是Prefetch的限制。任何人都可以在这里发现可能发生的事情吗?

So either there is something wrong with my code, or a limitation on Prefetch. Can anyone shed some light on what might be happening here?

感谢
Nathan

Thanks Nathan

推荐答案

由于您正在抓取预取数据深度的三个级别,所以该属性将存在于最后一个级别之前。这意味着你必须这样做才能访问它:

Since you're grabbing three levels deep of prefetch data, the property will exist on the level before the last one. What this means it that you'd have to do something like this to access it:

bevtank_set__package_set__checkout_set
for pt in product_types:
    for bevtank in pt.bevtank_set.all():
        for package in bevtank.package_set.all():
            co = package.checkouts_due

Django将不会将您的多个关系的预取整合到原始查询的模型中的单个属性中。您必须深入研究具有与您最终想要的那种型号有多对多或相反的FK关系的属性。

Django will not consolidate your prefetch across multiple relationships into a single property on the originally queried model. You have to drill down to the property that has the many-to-many or reverse FK relationship to that model you ultimately want.

这篇关于使用多级反向查找来预取对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆