Faraz Khan
Faraz Khan

Reputation: 85

Django's ManyToManyField column of model isn't showing in database

I created two models in Django and used 'subcode' as ManyToManyField to create a relation between them.

But after migration the column with ManyToManyField is missing in the database table.

class Subject(models.Model):
    Subject_Name = models.CharField(max_length=200)
    Subject_Code = models.CharField(max_length=200)
    Max_Marks = models.IntegerField()
    Course = models.CharField(max_length=200)
    Branch = models.CharField(max_length=100)
    Semester = models.IntegerField()

    def __str__(self):
        return self.Subject_Code

class Marks(models.Model):
    roll = models.IntegerField()
    subcode = models.ManyToManyField(Subject,related_name='subjects',default=2)
    marks = models.IntegerField()
    sheet = models.FileField(upload_to='marksheet')

I checked the table for "Marks" model. But it only has (id,roll,marks,sheet) and it is missing the 'subcode' column.

And now I cannot save 'subcode' using form because the 'subcode' column is missing in the table. How to fix this ?

Upvotes: 1

Views: 1521

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476659

Short answer: this is expected behavior.

A ManyToManyField is not stored as a column in a relational database. A many-to-many relation is defined as a table. Indeed, a table with two ForeignKeys, one to the "source" model (so Marks), and one to the "target" model (so Subject). This is a standard way to implement this, see for example the Wikipedia article on Many-to-many (data model).

In fact Django makes a model itself for that. You can obtain this with:

Marks.subcode.through

In your database, this model will probably be named appname_marks_subcode.

For example if you look at this in MySQL, you will see:

mysql> desc appname_marks_subcode;
+------------+---------+------+-----+---------+----------------+
| Field      | Type    | Null | Key | Default | Extra          |
+------------+---------+------+-----+---------+----------------+
| id         | int(11) | NO   | PRI | NULL    | auto_increment |
| marks_id   | int(11) | NO   | MUL | NULL    |                |
| subject_id | int(11) | NO   | MUL | NULL    |                |
+------------+---------+------+-----+---------+----------------+

Upvotes: 6

Related Questions