1. 程式人生 > >第六章:Django對mySQL資料庫的增刪改查操作

第六章:Django對mySQL資料庫的增刪改查操作

上一章中介紹了用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'})