Sergio
Sergio

Reputation: 33

Django - models.ForeignKey

Thanks for checking this out.

Silly doubt of mine:

I have the following models defined in Django:

class School(models.Model):
    name = models.CharField(max_length=256)
    principal = models.CharField(max_length=256)
    location = models.CharField(max_length=256)

    def __str__(self):
        return self.name

class Student(models.Model):
    name = models.CharField(max_length=256)
    age = models.PositiveIntegerField() # positive integer only accepts positives
    school = models.ForeignKey("School", related_name='students', on_delete=models.CASCADE)

    def __str__(self):
        return self.name

My question is: How does Django knows to pick the School.name field as a match for the foreign key school? As when I check on the Admin page and add a student, I can select the name of the school (as the foreign key). Name: Age: School = (drop down with the name of the schools)

Is it the order of the elements or something else?

Thanks again!

Upvotes: 2

Views: 1245

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477676

It does not, it uses the primary key by default. It renders the school with self.name because that is what __str__ returns.

So for example if you make a ModelChoiceField, then it will render HTML that looks like:

<select name="school">
    <option value="1">Name of School 1</option>
    <option value="2">Name of School 2</option>
    <option value="3">Name of School 3</option>
</select>

So when you submit the form, Django retrieves the primary key. The Name of School 1, is obtained because it calls str(…) [Python-doc] on the model objects. This will in its turn, if you specified it, call __str__, and the result of __str__ will be used to render the school. But for example in URLs, forms, etc. the primary key is used to retrieve data from the database.

Upvotes: 2

Related Questions