Operation table records of ORM in Django

Add table record

Add normal fields

   #方法一
    book_obj = Book(title='book7',publishDate='2011-05-02',price=200,publish_id=1)
    book_obj.save()
    
    #方式二
    Book.objects.create(title='book8',publishDate='2014-05-02',price=200,publish_id=1)

Add foreign key field

   #方法一
    publish_obj = Publish.objects.get(nid=1)
    Book.objects.create(title='book7',publishDate='2011-05-02',price=200,publish=publish_obj)
    
    #方法二
    Book.objects.create(title='book8', publishDate='2014-05-02', price=200, publish_id=1)

Many-to-many fields

  # Many-to-many fields 
    book_obj = Book.objects.create(title= ' book9 ' , publishDate= ' 2015-05-02 ' , price=200, publish_id=1 )
    author_1 = Author.objects.create(name='a1',age=20)
    author_2 = Author.objects.create(name='a2',age=23)
    book_obj.authors.add(author_1,author_2) #Add a specific model object to the associated object collection 
    book_obj.authors.create() #Create                and save a new object

    #Release the relationship 
    book_obj.authors.remove() #Remove a specific object from the associated object collection 
    book_obj.authors.clear() #Clear   the associated object collection 
    book_obj.authors.set(author_1) #Empty first , then set up
  
  # For all types of associated fields, add(), create(), remove() and clear(), set() will immediately update the database. At either end of the association, there is no need to call the save() method again

Modify table records

  update is a method of the QuerySet object, get returns a model object, there is no update method. The update() method is valid for any QuerySet, which means that you can update multiple records at the same time, and the update() method returns an integer value representing the number of records affected.

    
    #Method one 
    author_obj = Author.objects.get(id=5 )
    author_obj.name = 'jane'
    author_obj.save()

    #方式二
    Author.objects.filter(id=5).update(name='jane')

delete table record

   The delete method is delete(), which deletes the object immediately when it runs without returning any value

  You can also delete multiple objects at once, each QuerySet has a delete method that deletes all objects in the QuerySet at once.

  In any case, the delete() method in a QuerySet uses only one SQL statement to delete all objects at once, not every object. If you want to use the delete() method customized in the model, you need to call the delete method yourself

Book.objects.filter(publishDate__year='2011').delete()

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325207253&siteId=291194637