Home > OS >  Adding Foreign Key to model - Django
Adding Foreign Key to model - Django

Time:11-24

I am a novice in django. So please hear me out.

I have 2 models:

1.

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 model's selected_plan_id is Plans id. Which model should i add foriegn key to? and how?

So far i have started learning django,

CodePudding user response:

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)

CodePudding user response:

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.

CodePudding user response:

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.

  • Related