How do I insert data in Django with a foreign key (one-to-many and many-to-many) in the DB?

Source: Internet
Author: User

The data table structure you need to insert is as follows:

[Python]View Plaincopy
    1. Class UserInfo (models. Model):
    2. USER_ID =models. Autofield (primary_key=True)
    3. User_name=models. Charfield (max_length=20,unique=True)
    4. Depart=models. ForeignKey (Departmentinfo)
    5. 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
    1.           
    2.         d1=departmentinfo.objects.get (depart_id= 1)  #  d1 represents the userinfo of the foreign key data   
    3.         r1=role.objects.get (role_name=role)          #  r1 represents UserInfo's many-to-majority   
    4.         u1=userinfo (User_name=name,user_pwd=password, SEX=SEX,MOBILENO=MOBILE,EMAIL=EMAIL,DEPART=D1)   
    5.          u1.save ()   
    6.         u1.role.add (r1 )   
    7.         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
        • PS, if you decide to update or insert it?
        • obj, created = DeployPool.objects.update_or_create (
          AA=AA)
          Print obj, created

How do I insert data in Django with a foreign key (one-to-many and many-to-many) in the DB?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.