gpt4 book ai didi

python - Django查询优化: find a list of objects based on a many-to-one to a many-to-many

转载 作者:行者123 更新时间:2023-12-01 06:09:59 28 4
gpt4 key购买 nike

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

总结

  • 对象 A 与其自身具有非对称的多对多关系。
  • 对象 B 与对象 A 具有多对一关系。
  • 给定一个 ObjectB,我需要一组其他 ObjectB,它们是与我们的 关联的 ObjectAs 的子级ObjectB 的父对象 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 列表,从而不必运行这个极其低效的循环?

最佳答案

Given an ObjectB, I need a set of other ObjectBs that are the children of the ObjectAs that are associated with our ObjectB's parent 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查询优化: find a list of objects based on a many-to-one to a many-to-many,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6385964/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com