Django查询外键

时间:2013-11-11 19:01:25

标签: django django-models

我有下面的模型,如何获得city id

的邮政编码
from django.db import models

class City(models.Model):
    # ...
    pass

class Location(models.Model):
    # ...
    city= models.ForeignKey(City)

class Postcode(models.Model):
    # ...
    location = models.ForeignKey(Location)
    postcode = models.CharField(max_length=10)

1 个答案:

答案 0 :(得分:4)

你可以这样做::

post_codes = Postcode.objects.filter(location__city__pk = city_id)

您可以在lookups that span relationships here上阅读更多内容。 __可以跨越外键可以是任何级别的深层