Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Django model.py model.foreignkey()
#1
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
Reply
#2
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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Django: View is unable to find attributes of database model pythonpaul32 0 484 Dec-07-2023, 06:38 PM
Last Post: pythonpaul32
  Querying Django model db - from Jose Portilla’s Udemy course Drone4four 2 1,658 Aug-09-2022, 09:25 AM
Last Post: Addweb
Photo After using models.Model on my class Im getting 'ImproperlyConfigured' error Django khavro 1 2,150 Apr-05-2021, 03:11 PM
Last Post: SheeppOSU
  Selenium Page Object Model with Python Cryptus 5 3,894 Aug-19-2020, 06:30 AM
Last Post: mlieqo
  [Django]calculate value in model smabubakkar 0 1,629 Apr-15-2020, 03:40 PM
Last Post: smabubakkar
  Django: How to automatically substitute a variable in the admin page at Django 1.11? m0ntecr1st0 3 3,247 Jun-30-2019, 12:21 AM
Last Post: scidam
  Need your help to fix my database relationship in Django model PrateekG 0 2,632 Jul-02-2018, 11:08 AM
Last Post: PrateekG
  Django not saving model in management command F2Andy 1 3,225 Jun-02-2018, 03:17 PM
Last Post: F2Andy
  How do I make a Django model from a tab-delimited data file? newbietostuff 0 2,501 Jan-09-2018, 02:44 AM
Last Post: newbietostuff
  Django field model for HTML parser? Drone4four 0 4,118 Nov-15-2017, 02:43 AM
Last Post: Drone4four

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020