HenryJ
HenryJ

Reputation: 55

Django model.py models.ForeignKey()

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

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?

from django.db import models

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.

Upvotes: 2

Views: 3950

Answers (2)

Vikas Periyadath
Vikas Periyadath

Reputation: 3186

Foreign key is establishing to the column which has primary key. only one primary key will be in a table,
So in django you only have to give the table name. It will automatically establish with the column which having primary key.

If you are not mentioning any primary key in your column django models will automatically add one id column which will have unique not null integer value for each entry.

If you want to explicitly give foreign key to a specific column you can do like this :

models.ForeignKey(TableName, db_column='Column_name')

Upvotes: 1

Jahongir Rahmonov
Jahongir Rahmonov

Reputation: 13723

You can understand your classes as a table in the database ONLY IF it extends models.Model class.

This becomes a table:

class Order(models.Model):
    pass

This will not become a model:

class SomeHelper():
    ....

As for the ForeignKey, it will automatically be tied to the primary key of the other model. You can change that by setting to_field in that ForeignKey but the default is pk:

models.ForeignKey(Bar, to_field='non-pk-field')

Upvotes: 2

Related Questions