当前位置: 移动技术网 > IT编程>脚本编程>Python > Django ORM (三) 查询,删除,更新操作

Django ORM (三) 查询,删除,更新操作

2019年05月22日  | 移动技术网IT编程  | 我要评论

中国银行网银首次登陆,骂人宝典不带脏字,廉洁从业学习心得

orm 查询操作

修改 views.py 文件

from django.shortcuts import render, httpresponse
from app01 import models
from  app01.models import book,author,publisher

def data_oper(req):
    # 获取 book 表 id 为2的价格
    book = models.book.objects.filter(id=2).values("price")
    print(book)

    # 获取 author 表 id 为 1 的名字
    authors = models.author.objects.filter(id=1)[0]
    print(authors)

    # 获取 author 表 id 为 3 名字
    author1 = models.author.objects.get(id=3)
    print(author1)

    # 以 id 为倒序排列输出记录
    author2 = models.author.objects.order_by("-id")
    print(author2)

    return httpresponse("hello world")

orm 删除操作

修改 views.py 文件

from django.shortcuts import render, httpresponse
from app01 import models
from  app01.models import book,author,publisher

def data_oper(req):
    # 多对多的情况下,删除 book id 为1,author id 大于0的记录
    book = models.book.objects.filter(id=2)[0]
    authors = models.author.objects.filter(id__gt=0)
    book.authors.remove(*authors)

    # 删除单条记录,删除 book 表中 id 为 1 的记录
    models.book.objects.filter(id=1).delete()



    return httpresponse("hello world")

orm 更新操作

修改 views.py 文件

from django.shortcuts import render, httpresponse
from app01 import models
from  app01.models import book,author,publisher

def data_oper(req):
    # 把 author id 为 3 的 name 改为 katy
    author = models.author.objects.get(id=3)
    author.name = "katy"
    author.save()

    return httpresponse("hello world")

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网