python - Create new record with the self rererenced Foreignkey relation -


below models.py , made self reference foreignkey relationship.

class emp_details(models.model):     emp_id              =   models.autofield(primary_key = true)      emp_first_name      =   models.charfield(max_length = 50,null = false)     emp_manager_id      =   models.foreignkey('self')  a1 = emp_details(emp_first_name = "ramesh",emp_manager_id = 2) a1.save() 

here trying create new record. got following error:

valueerror: cannot assign "'2'": "emp_details.emp_manager_id" must "emp_details" instance. 

how can create new record self rererenced foreignkey relation?

in case, emp_manager_id foreign key field, should assign id emp_manager_id_id.

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

it better change field name emp_manager. note it's recommended use camelcase model name, empdetail better emp_details. putting together, 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 emp_manager foreign key, can assign id emp_manager_id.

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

if want set emp_manager object itself, need save object database first, gets primary key.

a1 = empdetail(emp_first_name="ramesh") a1.save() a1.emp_manager = a1  # 'a1.emp_manager_id = a1.id' instead  a1.save() 

for work, you'll need set null=true on foreign key can save object without setting emp_manager.

emp_manager = models.foreignkey('self', null=true) 

Comments

Popular posts from this blog

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12:test (default-test) on project.Error occurred in starting fork -

windows - Debug iNetMgr.exe unhandle exception System.Management.Automation.CmdletInvocationException -

configurationsection - activeMq-5.13.3 setup configurations for wildfly 10.0.0 -