The data table structure you need to insert is as follows:
[Python]View Plaincopy
- Class UserInfo (models. Model):
- USER_ID =models. Autofield (primary_key=True)
- User_name=models. Charfield (max_length=20,unique=True)
- Depart=models. ForeignKey (Departmentinfo)
- Role=models. Manytomanyfield (Role)
* Note: From the above class can be seen userinfo in addition to the general table items, there is a foreign key, and a many-to-many field
The Insert data method is as follows:
[Python]View Plaincopy
-           
- d1=departmentinfo.objects.get (depart_id= 1) # d1 represents the userinfo of the foreign key data
- r1=role.objects.get (role_name=role) # r1 represents UserInfo's many-to-majority
- u1=userinfo (User_name=name,user_pwd=password, SEX=SEX,MOBILENO=MOBILE,EMAIL=EMAIL,DEPART=D1)
- u1.save ()
- u1.role.add (r1 )
- u1.save ()
Summarize:
- Normal data entry: Direct insertion
- FOREIGN key data item: Get the foreign key to insert first, and then insert it with normal want
- Many-to-most items: Gets the many-to-most data items to insert, and after save for normal and foreign key data items in the table, use the. Add method to add
How do I insert data in Django with a foreign key (one-to-many and many-to-many) in the DB?