简体   繁体   English

Django-过滤prefetch_related

[英]Django - Filtering prefetch_related

I am having trouble with filtering one of my views. 我在过滤我的一种观点时遇到了麻烦。 It is a DetailView, that also display lots of additional tables. 它是一个DetailView,还显示许多其他表。 I have my models as such: 我有这样的模型:

 class Pipeline(models.Model):

 class Stage(models.Model):
     pipeline = models.ForeignKey(Pipeline, related_name='stages')

 class Opportunity(models.Model):
     status = ....
     stage = models.ForeignKey(Stage, related_name='opportunities')

 class EstateActivity(models.Model):
      time = models.DateTimeField(...)
      opportunity = models.ForeignKey(EstateOpportunity, related_name='activities')

Now, I am displaying Pipeline DetailView. 现在,我正在显示Pipeline DetailView。 In this DetailView I use prefetch related on all these models 在这个DetailView中,我使用与所有这些模型相关的预取

qs.filter(users=self.request.user).prefetch_related('stages__opportunities__activities')

One pipeline contains many stages, and each stage containst many opportunities etc. However, I need to filter out firstly opportunities by their status(which can be obtained from URL). 一个管道包含多个阶段,每个阶段包含许多机会等。但是,我需要首先根据机会的状态(可以从URL获取)过滤掉机会。 And to each opportunity I need to filter one specific activity (most recent activity and if such doesn't exist, then most recent from the past). 对于每个机会,我需要过滤一个特定的活动(最近的活动,如果不存在,则是过去的最新活动)。 So far, I tried using extra, however this doesn't work. 到目前为止,我尝试使用额外的功能,但这不起作用。 I fail to come up with a solution that doesn't involve hitting database each time. 我无法提出一个解决方案,该解决方案不需要每次都访问数据库。 Also, I can't just select it each model one by one 而且,我不能只是一个一个地选择每个模型

context['opportunities'] = Opportunity.objects.filter(user=..., ..pipeline=self.object, status=.....)

because I need to have the relations with Stage for template. 因为我需要与Stage建立模板的关系。 If I just iterate over context['opportunities'] and add the desired Activity to each one, it's gonna hit database each time. 如果我只是遍历context ['opportunities']并将所需的Activity添加到每个活动中,则每次都会访问数据库。 Sadly, the prefetch_related filtering is only in the development version, with stable release in about 5 months. 可悲的是,与prefetch_related有关的过滤仅在开发版本中,并在大约5个月内稳定发布。

Would select_related work for you instead? select_related会为您工作吗?

qs.filter(users=self.request.user).select_related('stages')

Alternatively, work backwards: 或者,向后工作:

opportunities = EstateActivity.objects.filter(opportunity__stage__pipeline__users=self.request.user)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM