[Fixed]-Create new record with the self rererenced Foreignkey relation

1👍

In your case, emp_manager_id is the foreign key field, so you should assign the id to emp_manager_id_id.

a1 = emp_details(emp_first_name = "ramesh", emp_manager_id_id=2)

It would be better to change the field name to emp_manager. Note it’s recommended to use CamelCase for your model name, so EmpDetail is better than emp_details. Putting that together, you have:

class EmpDetail(models.Model):
    emp_id = models.AutoField(primary_key = True) 
    emp_first_name = models.CharField(max_length = 50,null = False)
    emp_manager = models.ForeignKey('self')

Now that emp_manager is the foreign key, you can assign the id to emp_manager_id.

a1 = EmpDetail(emp_first_name="ramesh", emp_manager_id_id=2)

If you want to set emp_manager to the object itself, then you need to save the object to the database first, so that it gets a primary key.

a1 = EmpDetail(emp_first_name="ramesh")
a1.save()
a1.emp_manager = a1  # You could do 'a1.emp_manager_id = a1.id' instead 
a1.save()

For this to work, you’ll need to set null=True on the foreign key so that you can save the object without setting emp_manager.

emp_manager = models.ForeignKey('self', null=True)

Leave a comment