I am learning Django, and I have this basic model:
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. From Django docs I found that I should use foreign key, but the backward query is causing problems. 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. You can find the Countries
attached to each Continent
by using the reverse ForeignKey
relationship:
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
.
I agree with xyres . Also, you can define related_name in ForeignKey like:
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.