在Django上使用select_related进行过滤

时间:2014-02-27 10:30:10

标签: django django-queryset django-select-related

我对使用过滤器操作的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

我要做的是,根据另一个参数 attribute1 (来自B类),通过在键 related_C 上对B类进行过滤来获得A类。 为了正确说明,我在班级C中有一个函数 get_class_A(self)

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

它返回类B的QuerySet。我想要做的是遵循指向A的ForeignKey,以便将B的这个QuerySet转换为对象列表A.

我尝试了各种各样的事情,例如:

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

和一些变化,但没有任何效果。有谁知道怎么做?

由于

1 个答案:

答案 0 :(得分:3)

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

你所描述的内容很像A和C之间的ManyToMany关系。如果你这样声明它,并通过将B指定为through模型来包含你的额外attributes,Django将会为你创造A和C之间的关系。

此外,select_related()与过滤结果无关,它只是一个工具,可以让您减少数据库查询的数量。来自docs

  

这是一个性能提升器,它会导致单个更复杂的查询,但意味着以后使用外键关系不需要数据库查询。

相关问题