假设我有以下模型:
# 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'