具有多个LEFT联接的ORM查询

时间:2019-04-16 16:26:07

标签: python django django-models

玩具示例:假设我有以下模型:

# Person ---lives_in--> City ---part_of---> State

class Person(models.Model)
    name = models.CharField(max_length=100)
    lives_in = models.ForeignKey('City', on_delete=models.CASCADE)

class City(models.Model)
    name = models.CharField(max_length=100)
    part_of = models.ForeignKey('State', on_delete=models.CASCADE)

class State(models.Model):
    name = models.CharField(max_length=100)

如何获取使用Django ORM处于特定状态的人的名单?

在常规SQL中,类似

SELECT p.* 
FROM person p
LEFT JOIN city c ON (p.lives_in = c.id)
LEFT JOIN state s ON (c.part_of = s.id)
WHERE c.name = 'MA'

1 个答案:

答案 0 :(得分:1)

您可以使用ValidityAuditStrategy表示法遍历这些关系。

__
  

https://docs.djangoproject.com/en/2.2/topics/db/queries/#lookups-that-span-relationships