简体   繁体   English

在Django上使用select_related进行过滤

[英]filter with select_related on Django

I have a problem with the usage of select_related feature of Django with the filter operation, here's my problem, I have three classes : 我在过滤器操作中使用Django的select_related功能时遇到问题,这是我的问题,我有三个类:

class A:
   # various fields here

class B(models.model):
   related_A = models.ForeignKey(A)
   related_C = models.ForeignKey(C)
   attribute1 = models.CharField(..)
   # Other attributes

class C(models.model):
   # Attributes

What I'm trying to do is, getting class A by filtering on class B on the key related_C according to another parameter attribute1 (from class B). 我想做的是,根据另一个参数attribute1 (来自类B),通过对关键字related_C上的类B进行过滤,来获取类A。 To illustrate it properly, I have a function get_class_A(self) in my class C 为了正确说明,我在类C中有一个函数get_class_A(self)

get_class_A(self,param):
   classes_B = B.objects.filter(related_C = self,attribute1 = param)

It returns a QuerySet of classes B. What I want to do is to follow the ForeignKey pointing to A in order to transform this QuerySet of B into a list of objects A. 它返回一个类B的QuerySet。我要做的是跟随ForeignKey指向A,以便将该B的QuerySet转换为对象A的列表。

I tried various things such as : 我尝试了各种事情,例如:

classes_A = B.objects.select_related('A').filter(related_C = self, attribute1 = param)

and some variations but nothing worked. 和一些变化,但无济于事。 Does anyone knows how to do this ? 有谁知道该怎么做?

Thanks 谢谢

def get_class_A(self, param):
    return A.objects.filter(b__related_c=self, b__attribute1=param).distinct()

What you've described looks a lot like a ManyToMany relationship between A and C. If you declare it as such, and include your extra attributes by specifying B as a through model, Django will create the relationship between A and C for you. 您所描述的内容看起来很像A与C之间的ManyToMany关系。如果这样声明,并通过将B指定为直通模型来包含额外的attributes ,则Django会为您创建A与C之间的关系。

Also, select_related() has nothing to do with filtering results, it's just a tool that can allow you to reduce the number of database queries. 另外, select_related()与过滤结果无关,它只是一个工具,可以使您减少数据库查询的次数。 From the docs : 文档

This is a performance booster which results in a single more complex query but means later use of foreign-key relationships won't require database queries. 这可以提高性能,从而导致单个更复杂的查询,但意味着以后使用外键关系将不需要数据库查询。

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

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