天天看點

Djang-Mysql配置及使用python-shell管理資料庫配置資料庫:python-shell的使用:

在開始本片部落格之前,請確定您已經安裝mysql和python-mysql

配置資料庫:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'test',    #選擇連接配接的資料庫,根據自己的資料庫進行填寫
        'USER':'root',    #填寫使用者名
        'PASSWORD':'123456',    #填寫資料庫的密碼
        'Host':'127.0.0.1',
        'Port':'',
    }
}
           

預設是sqlite的,如果要使用mysql的要将配置改為mysql的配置

配置完成後,我們開始建立我們的應用:

python manage.py startapp blog 
           

進入到建立的項目blog中:cd blog

找到檔案models.py進行編輯添加子產品

class Passage(models.Model):
    name= models.CharField(max_length=30)
    author = models.CharField(max_length=20)
    pubtime = models.CharField(max_length=12)
    website = models.URLField()

    def __str__(self):
        return self.name

class Author(models.Model):
    name = models.CharField(max_length=10)
    emal = models.CharField(max_length=30)
    city = models.CharField(max_length=10)

    def __str__(self):
        return self.name
           

文章有屬性:文章名,作者,釋出時間,網址

作者有屬性:姓名,郵件,城市

__str__(self):是為了在python-shell中更好的檢視,當然,還有其他的作用就不再這裡說了,這個函數很友善的,提倡使用

然後,我們找到settings.py檔案,把我們的‘blog’子產品加入進去

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'blog',
)
           

接着,我們便開始将模型的資料添加到mysql中了

添加之前,先驗證下模型:

python manage.py check    --驗證模型
           

确認有效後,運作以下指令,告訴Django你對模型做了修改(這裡是建立了模型)

python manage.py makemigrations blog
           

你應該會看到下面的輸出:

Migrations for 'blog':
  0001_initial.py:
    - Create model Author
    - Create model Passage
           

Django把模型(資料庫模式)的改動自動存儲在遷移中。遷移就是磁盤中的檔案。運作上述指令後,blog應用的migretions檔案夾裡會出現一個0001_initial.py的檔案。

sqlmigrate指令的參數是遷移的名稱,輸出結果是相應的SQL:

python manage.py sqlmigrete blog 0001
           

運作後可以看見他對資料庫進行的操作:

BEGIN;
CREATE TABLE `blog_author` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `name` varchar(10) NOT NULL, `emal` varchar(30) NOT NULL, `city` varchar(10) NOT NULL);
CREATE TABLE `blog_passage` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `name` varchar(30) NOT NULL, `author` varchar(20) NOT NULL, `pubtime` varchar(12) NOT NULL, `website` varchar(200) NOT NULL);

COMMIT;
           

Django會為各個表添加主鍵。即id字段

sqlmigrate并不會建立表, 其實他根本不接觸資料庫,隻是在螢幕上輸出Django即将執行的SQL。如果願意可以将中間的SQL語句複制到資料庫用戶端裡執行。然而,Django為送出SQL提供了更加簡單的方式:

python manage.py migrate
           

運作這個指令後會看到以下資訊:

Operations to perform:
  Synchronize unmigrated apps: staticfiles, messages
  Apply all migrations: admin, blog, contenttypes, auth, sessions
Synchronizing apps without migrations:
  Creating tables...
    Running deferred SQL...
  Installing custom SQL...
Running migrations:
  Rendering model states... DONE
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying blog.0001_initial... OK
  Applying sessions.0001_initial... OK
           

可以從進入資料庫看到:Django建立的資料表

Djang-Mysql配置及使用python-shell管理資料庫配置資料庫:python-shell的使用:

當你對models.py檔案做了修改後,應該将資料更新到資料庫:

python manage.py makemigrations
python manage.py migrate
           

python-shell的使用:

python manage.py shell
           

導入子產品:

Python 2.7.15 |Anaconda, Inc.| (default, Dec 10 2018, 21:57:18) [MSC v.1500 64 bit (AMD64)]
Type "copyright", "credits" or "license" for more information.

IPython 5.8.0 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: from blog.models import Author
           

檢視其中的資料(為了顯示,已經添加了兩個元組):

In [2]: Author.objects.all()
Out[2]: [<Author: 代國平>, <Author: 肖堯>]
           

一般來說,顯示的是

Out[2]: [<Author: object>, <Author: object>]
           

回想一下,我之前的models.py檔案中是不是寫了一個函數__str__(self),目的就是為了提供便利,當然也不僅僅是這個作用。

插入和更新資料:

newdata=Author(id='3',name="楊培傑",“[email protected]”,"許昌")
newdate.save()
           

在資料庫中就能 看到新插入的資料元組了

過濾資料

因為all()是一次性從資料庫中找出所有的資料,然而我們在實際的使用中是有選擇的查找資料,處理他的子集。在DjangoAPI中,可以使用filter()方法來過濾資料:

Author.objects.filter(name="代國平")
           

`其他查找類型:

Author.objects.filter(name__contains='代')
[<Author:代國平>]
           

支援的其他查找類型還有icontains(不區分大小寫的LIKE),startwith,endwith,range(SQL的between語句)。這裡不做詳細介紹。

`檢索單個對象

filter()傳回的是一個查詢集合(清單),有時候,需要擷取單個對象,此時應該使用get()方法:

Author.objects.get(id=1)
<Author: 代國平 >    #查找單個對象

-----------------------------------------------------------------------------------------
Author.objects.get(city="成都")    #得到多個對象會引發錯誤
Traceback(most recent call last):
...
MultipleObjectReturned:get() return more than one Author --it return 2!Lookup paraments were {'city':'成都'}
-----------------------------------------------------------------------------------------

Author.objects.get(name='不存在的人')    #查詢不存在的對象也将導緻異常
Traceback (most recent call last):
...
DoesNotExist: Author mathing query does not exist.
           

·排序資料

Author.objects.order_by("id")    #可以根據任何字段進行排序,也可以多個參數order_by("id","name")
[<Author:代國平>,<Author:肖堯>,<Author:楊培傑>]

Author.objects.order_by("-id")    #加上一個-号進行逆向排序
[<Author:楊培傑>,<Author:肖堯>,<Author:代國平>]
           

還有一種方法,是在modles.py的下添加:

class Meta:
    ordering=['id']
           

更新資料:

Author.objects.filter(name="代國平").update(eml="[email protected]")
           

删除對象:

Author.objects.all().delete()    #删除所有
Author.objects.filter(name="楊培傑").delete()