上一章中介绍了用Django连接MySQL数据库,本章介绍最基本的增删改查操作,继续利用上一章创建的表

一、新增数据

  • 1、引入数据模块

    from models import BlogModel
  • 2、利用模型创建数据

    blogModel = BlogModel(title='我是第一篇文章标题',content='我是第一篇文章的内容')
  • 3、利用save方法提交到数据库

    blogModel.save()
  • 4、完整代码

    
    # -*- coding: utf-8 -*-
    
    from __future__ import unicode_literals
    
    from django.shortcuts import render
    from models import BlogModel
    
    def index(request):
        blogModel = BlogModel(title='我是第一篇文章标题',content='我是第一篇文章的内容')
        blogModel.save()
        return render(request,'book_index.html',{'msg':'HELLO WORD'})

二、查询所有数据

  • 1、引入数据模型
  • 2、利用objects查询数据.all()返回的是一个list数据

    blogModel = BlogModel.objects.all()
  • 3、完整代码

    
    # -*- coding: utf-8 -*-
    
    from __future__ import unicode_literals
    
    from django.shortcuts import render
    from models import BlogModel
    
    def index(request):
        blogModel = BlogModel.objects.all()
        print '*'*100
        print blogModel
        print '*'*100
        return render(request,'book_index.html',{'msg':'HELLO WORD'})

三、查询第一条数据(在查询所有的基础上下first)返回的数据是一个object

  • 1 完整代码

    
    # -*- coding: utf-8 -*-
    
    from __future__ import unicode_literals
    
    from django.shortcuts import render
    from models import BlogModel
    
    def index(request):
        blogModel = BlogModel.objects.all().first()
        print '*'*100
        print blogModel
        print '*'*100
        return render(request,'book_index.html',{'msg':'HELLO WORD'})

四、根据id查询数据(利用get(条件))返回的也是一个object

  • 1、完整代码

    
    # -*- coding: utf-8 -*-
    
    from __future__ import unicode_literals
    
    from django.shortcuts import render
    from models import BlogModel
    
    def index(request):
        blogModel = BlogModel.objects.get(id=1)
        print '*'*100
        print blogModel
        print '*'*100
        return render(request,'book_index.html',{'msg':'HELLO WORD'})

五、删除数据(返回的是删除的这条数据)

  • 1、先利用上面的方式查询到数据
  • 2、利用delete删除查询到的这条数据
  • 3、完整代码

    
    # -*- coding: utf-8 -*-
    
    from __future__ import unicode_literals
    
    from django.shortcuts import render
    from models import BlogModel
    
    def index(request):
        blogModel = BlogModel.objects.get(id=1)
        aa = blogModel.delete()
        return render(request,'book_index.html',{'msg':'HELLO WORD'})

六、修改数据

  • 1、先查询数据
  • 2、重新给字段赋值
  • 3、提交数据
  • 4、完整代码

    
    # -*- coding: utf-8 -*-
    
    from __future__ import unicode_literals
    
    from django.shortcuts import render
    from models import BlogModel
    
    def index(request):
        blogModel = BlogModel.objects.get(id=2)
        blogModel.title = '我修改后的数据'
        blogModel.content = '文章内容'
        blogModel.save()
        return render(request,'book_index.html',{'msg':'HELLO WORD'})
Logo

更多推荐