我有一个丑陋的循环,在Django中它是一个创可贴,我想将其优化为一个联接。我将其分解为最基本的结构,以帮助简化问题。我希望其他人以前遇到过类似的情况-如果没有,我将在最终解决问题时分享答案。

总结一下


对象A与自身具有非对称的多对多关系。
对象B与对象A具有多对一关系。
给定一个ObjectB,我需要一组其他ObjectB,它们是与我们的ObjectB的父ObjectA关联的ObjectA的子代。


我敢肯定,有更多数据库经验的人可以说出更好的短语(如果您对此关联有更好的描述,请留下评论)。

这是我在Django中使用的结构的基本示例,以及正在运行的某种循环:



class ObjectA(models.Model):
    object_a_rules = models.ManyToManyField("self", symmetrical=False, through='ObjectARule')

class ObjectARule(models.Model):
    object_a_one = models.ForeignKey(ObjectA, related_name="object_a_before")
    object_a_two = models.ForeignKey(ObjectA, related_name="object_a_after")

class ObjectB(models.Model):
    object_a_association = models.ForeignKey(ObjectA)

    def that_annoying_loop_i_mentioned(self):
        object_a_rules_list = ObjectARule.objects.filter(object_a_one = self.object_a_association)
        #A list of all of the ObjectARules that have the ObjectA this ObjectB is associated with
        #as the first half of the many-to-many relationship.

        object_b_list = ObjectB.objects.all()
        #A list of all of the ObjectBs, may also be a filtered list

        for object_a_rule in object_a_rules_list:
            for object_b in object_b_list:
                if (object_a_rule.object_a_two == object_b.object_a_association):
                #if the second half of ObjectARule is the ObjectA of
                #the ObjectB in this list, then do something with that ObjectB.
                pass


Django如何通过联接获取ObjectB列表,这样就不必运行效率低下的循环了吗?

最佳答案

给定一个ObjectB,我需要一组
  其他的ObjectB是子对象
  关联的ObjectAs
  与我们的ObjectB的父ObjectA。


如果objb是给出的ObjectB,则可以按照以下步骤进行操作:

objects = ObjectB.objects.filter(object_a_association__object_a_rules=objb.object_a_association)


或者,

objects = ObjectB.objects.filter(object_a_association__object_a_rules__objectb_set=objb)


另见Lookups that span relationships

关于python - Django查询优化:基于多对多对多查找对象列表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6385964/

10-09 20:15