使用Django 1.7'`Prefetch`

时间:2015-02-25 21:35:59

标签: python django

我正在尝试使用新的Prefetch解决问题,但我无法弄清楚如何使用它。

我有这些模特:

class Desk(django.db.models.Model):
    pass

class Chair(django.db.models.Model):
    desk = django.db.models.Foreignkey('Desk', related_name='chair',)
    nearby_desks = django.db.models.ManyToManyField(
        'Desk',
        blank=True,
    )

我想获取Desk的查询集,但它还应包含预取属性favorite_or_nearby_chairs,其值应等于:

Chair.objects.filter(
    (django.db.models.Q(nearby_desks=desk) | django.db.models.Q(desk=desk)),
    some_other_lookup=whatever,
)

Prefetch这可能吗?我无法弄清楚如何使用这些参数。

1 个答案:

答案 0 :(得分:0)

您不需要使用Prefetch。如果默认的prefetch_related无法执行您想要的操作,则只需使用Prefetch。

Chair.objects.select_related('desk').prefetch_related('nearby_desks')\
        .filter(Q(nearby_desks=desk) | Q(desk=desk))

<强>更新 使用预取:

nearby_desks_qs = Desk.objects.all()

Chair.objects.select_related('desk')\
    .prefetch_related(Prefetch('nearby_desks',
                               queryset=nearby_desks_qs,
                               to_attr='nearby_desks_qs'))\
    .filter(Q(nearby_desks=desk) | Q(desk=desk))