0
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?

3 Answers 3

2

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)
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.