Python Forum

Full Version: Django model.py model.foreignkey()
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi All,

I am a newbie on Django framework and a bit confused on the models.

1. When a "class" in the model.py, can I just understand it as "table" in database? For example, in the code below, "Test", "Contact", and "Tag" are all tables in the database used by Django?

2.
from django.db import models
 
# Create your models here.
class Test(models.Model):
    name = models.CharField(max_length=20)
 
class Contact(models.Model):
    name   = models.CharField(max_length=200)
    age    = models.IntegerField(default=0)
    email  = models.EmailField()
    def __unicode__(self):
        return self.name
 
class Tag(models.Model):
    contact = models.ForeignKey(Contact)
    name    = models.CharField(max_length=50)
    def __unicode__(self):
        return self.name
in the class "Tag", it is using models.ForeignKey(Contact), based on my understanding, the foreignkey should be established on one specific column of a table, but why the ForeignKey is establish on a table directly, i.e. Table "Contact"?

Any guidance is highly appreciated.

Best Regards,
Henry
When you designate a field as a ForeignKey of another model Django will tie they field to whatever the primary key is of the parent table. When you run your migrate commands Django will create a column with the name of 'id' set it to primary and auto increment. That is what would happen in the scenario you have provided.