Scrontch
Scrontch

Reputation: 3424

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

Upvotes: 4

Views: 464

Answers (1)

alecxe
alecxe

Reputation: 473903

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:

Upvotes: 3

Related Questions