Home > Blockchain >  What's a reverse foreignkey and a normal foreignkey
What's a reverse foreignkey and a normal foreignkey

Time:09-03

This a question from a Django noob, my question goes thus;

What is the difference between a normal foreignkey and a reverse relation and what is the difference. I always thought;

method 1

class State(models.Model):
    name = models.CharField()

class Country(models.Model):
    name = models.CharField()
    state = models.ForeignKey(State) # normal foreignkey

method 2

class Country(models.Model):
    name = models.CharField()

class State(models.Model):
    name = models.ForeignKey(Country) # reverse relation

What is the main difference between method 1 and 2 and when to use it.

CodePudding user response:

This is basically a database related question and I encourage you to read further about it.

a Foreign key relationship in Django translates to 1 to many relationship in database design.

In your example and real world 1 state can have 1 country and one country only. But a Country can have infinite (or n) number of states.

So in our country model we can't have infinite fields to represent all the states.

What we can do is we tell each state that which country they belong to.

so this is the right way to do it here.

class Country(models.Model):
    name = models.CharField()

class State(models.Model):
    name = models.CharField()
    country = models.ForeignKey(Country)

In the first method that you wrote each country can have 1 state but each state can belong to multiple countries.

  • Related