Table operation statement:
Books created more than one, publishers, authors, author information table as an example:
increase:
# -One
# (1) foreign key class attribute, a foreign key constraint object association attributes directly inserted
author_detail_obj=models.AuthorDetail.objects.get(id=4)
author_obj = models.Author.objects.create(author_name='脉动',author_birth='2010-10-10',author_detail=author_detail_obj)
# ( 2 ) a foreign key value into the specified fields
# author_obj = models.Author.objects.create(author_name='脉动', author_birth='2010-10-10',author_detail_id=4)
# Many-to
# ( A foreign key) class attribute, a foreign key constraint object association attributes directly inserted
publish_obj=models.Publish.objects.get(id=3)
book_obj=models.Book.objects.create(book_name='时光不散',book_price=22,book_publisher=publish_obj)
# ( 2 ) a foreign key value into the specified fields
# book_obj = models.Book.objects.create(book_name='时光不散', book_price=22, book_publisher=3)
# -Many ( object-based )
author_obj1=models.Author.objects.get(id=1)
author_obj2=models.Author.objects.get(id=3)
book_obj=models.Book.objects.get(book_name='小时光')
# (1) call the method passed in object attributes associated with objects inserted
book_obj.author.add(author_obj1,author_obj2)
# ( 2 ) method calls the object's properties directly into the id insert
# book_obj.author.add(1,3)
# book_obj.author.add(*[1,3])
Deleted ( multi-table are associated with the default cascading deletes, and delete operations as a single table of direct deleted ):
# -One
models.Author.objects.filter(author_name='无名').first().delete()
# Many-to
models.Book.objects.filter ( book_name = ' Perfect World ' ) .Delete ()
# -Many ( object-based )
author_obj1=models.Author.objects.get(pk=1)
= models.Author.objects.get author_obj2 ( author_name = ' Mr. Almost ' )
book_obj=models.Book.objects.filter(book_name='小时光')[0]
#remove designated Delete
# ( 1 ) using remove passing object parameters
book_obj.author.remove(author_obj1,author_obj2)
# ( 2 ) using remove pass parameters field
# book_obj.author.remove(author_obj1.id, author_obj2.id)
# book_obj.author.remove(1,2)
# book_obj.author.remove(*[1,2])
# Clear direct clear all
book_obj.author.clear()
change:
# 一对一
models.Author.objects.filter(author_name='差不多先生').update(author_name='金庸')
# 多对一
models.Book.objects.filter(book_price=22).update(book_price=11)
# 多对多(基于对象)
book_obj=models.Book.objects.get(id=5)
# 先清除再设置(set只能给一个参数,数字或者字符型数字均可)
book_obj.author.set([1,2,'7'])
在多表增删改操作中,一对一和多对一关系表与单表的操作一样;多对多(自动创建的第三张表)都是基于对象操作,使用多对多约束的属性(第三张表)调用orm提供的add、remove、clear、set方法进行增删改查操作,参数可以为指定的字段值,也可以使用指定的对象作为参数