Adding Foreign Key to model – Django

Question:

class Plans(models.Model):
    id = models.IntegerField(primary_key=True)
    name = models.CharField(max_length=255)
    plan_type = models.CharField(max_length=255)

class Order(models.Model):
    id = models.IntegerField(primary_key=True)
    selected_plan_id = models.IntegerField(primary_key=True)

Order‘s selected_plan_id is Plans‘s id.
Which model should I add a foreign key to? How?

Asked By: Jordan Flanagan

||

Answers:

First of all there are some bad ways to pointout:

  • two fields cannot be primary keys in a table
  • also django as default includes primary key id in every table, so no need to add id field.

You should be doing this way:

class Order(models.Model):
    selected_plan_id = models.ForeignKey(Plans, on_delete=models.CASCADE)
Answered By: ilyasbbu
class Order(models.Model):
    id = models.IntegerField(primary_key=True)
    selected_plan_id = models.IntegerField(primary_key=True)
Plain= models.ForeignKey(Plain)

Check the dependence of the table and after getting that made one key as foreign like in this one plain is not depend on the order. But the order depends on the plan.

Answered By: August Infotech

The solution that you are looking for

class Order(models.Model):
    id = models.IntegerField(primary_key=True)
    selected_plan_id = models.ForeignKey(Plans, on_delete=models.CASCADE)

The purpose of using models.CASCADE is that when the referenced object is deleted, also delete the objects that have references to it.
Also i dont suggest to you add ‘id’ keyword to your property, django makes automatically it. If you add the ‘id’ keyword to end of the your property like this case, you gonna see the column called ‘selected_plan_id_id’ in your table.

Answered By: tumer