djangoORM操做

表操做使用django集成的方法,数据库

好比有一张User表:User.objects.all()  返回一个Queryset对象(数据类型list),里面是User表的全部行封装成的User对象。django

User.objects是一个QuerySet实例。django查找一个对象显然是先查看是否内存中已经有了此对象,若是没有再去数据库查看。spa

 

增删改查的方法:code

  增:objects.create()方法,此方法直接修改数据库对象

    - 实例化一个子类对象,再用save()方法blog

      - 若是子类对象里面有多对多关系,
        那么须要给多对多关系字段添加数据,有1个方法内存

 

例子:ci

title=request.POST.get("title")
price=request.POST.get("price")
date=request.POST.get("date")
publish_id=request.POST.get("publish_id")
author_pk_list=request.POST.getlist("author_pk_list") # [1,2]       
book_obj=Book.objects.create(title=title,price=price,date=date,publish_id=publish_id),
上面这一步是在数据库生成这条数据,而后添加多对多关系:添加pk值能够,添加对象也可,多个添加用列表形式以下 book_obj.authors.add(
*author_pk_list)

 

    - 多条记录一次增长:使用save()方法,由于只要向数据库发起一次请求文档

  改:updata()方法,updata_or_create()方法,select_for_update()get

updata()

"""
更新当前QuerySet中的全部元素,将全部给定字段设置为适当的值
"""

 

select_for_update()

"""
返回一个新的QueReSET实例,该实例将选择更新锁定的对象。
"""

updata_or_create()

"""
Look up an object with the given kwargs, updating one with defaults
if it exists, otherwise create a new one.
Return a tuple (object, created), where created is a boolean
specifying whether an object was created.
"""

删:

 

官方文档参考

相关文章
相关标签/搜索