4

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 doesn't compile. (City is undefined in the definition of Country). Any suggestions?

Scrontch
  • 3,275
  • 5
  • 30
  • 45

1 Answers1

3

You can refer to the model by using 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

Also see:

Community
  • 1
  • 1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195