Django models, circular foreign keys

How to model the following relationship:

class Country(models.Model): # The capital city of this country capital = models.ForeignKey(City) ## other country stuff class City(models.Model): # The country where this city lies in country = models.ForeignKey(Country) ## other city stuff 

This obviously does not compile. (The city is undefined in the definition of a country). Any suggestions?

+4
source share
1 answer

You can reference a model using a string instead of a model class:

 class Country(models.Model): # The capital city of this country capital = models.ForeignKey('City', related_name='+') ## other country stuff 

See also:

+3
source

All Articles