[英]Django query by foreign key
I am learning Django, and I have this basic model: 我正在学习Django,并且具有以下基本模型:
from django.db import models
class Country(models.Model):
name = models.CharField(max_length=255,)
continent = models.ForeignKey('Continent')
class Continent(models.Model):
name = models.CharField(max_length=255, unique = True)
countries = ???
I want the Continent.countries attribute to return the matching countries, with continent-foreign key set to this continent. 我希望Continent.countries属性返回匹配的国家/地区,其中大陆-外键设置为此大陆。 From Django docs I found that I should use foreign key, but the backward query is causing problems. 从Django文档中,我发现我应该使用外键,但是向后查询引起了问题。 I have experimented a few ways, but as a beginner I cant find the "correct" way of doing this. 我已经尝试了几种方法,但是作为一个初学者,我找不到做到这一点的“正确”方法。 Any suggestions? 有什么建议么?
You don't need to create a countries
attribute in Continent
to establish a reverse relationship. 您无需在Continent
上创建countries
属性即可建立反向关系。 You can find the Countries
attached to each Continent
by using the reverse ForeignKey
relationship: 您可以使用反向的ForeignKey
关系找到与每个Continent
相连的Countries
:
continent = Continent.objects.get(name='Asia')
countries = continent.country_set.all()
The country_set
function is created by Django when you create a ForeignKey
relationship between Country
and Continent
. 当您在Country
和Continent
之间创建ForeignKey
关系时, country_set
函数由Django创建。
I agree with xyres . 我同意xyres 。 Also, you can define related_name in ForeignKey like: 另外,您可以在ForeignKey中定义related_name ,例如:
continent = models.ForeignKey('Continent', related_name='countries')
so that, you can easily get countries in a continent: 这样一来,您就可以轻松获得大洲的国家/地区:
continent.countries.all()
here, continent is object of the model Continent. 在这里, 大陆是大陆模型的对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.