【Mac系統 + Python + Django】之開發一個發佈會系統【Django模型(三)】

上一部分給你們介紹Django的視圖

接下來繼續來了解Django框架,來看第三部分,此部分是對數據庫的操做。

 

目錄:

 

 

1、設計系統表            返回目錄

首先打開sign/models.py,經過模型完成標的建立:sql

from django.db import models # Create your models here.

# 發佈會表
class Event(models.Model): name = models.CharField(max_length=100)             # 發佈會標題
    limit = models.IntegerField()                       # 參加人數
    status = models.BooleanField()                      # 狀態
    address = models.CharField(max_length=200)          # 地址
    start_time = models.DateTimeField("event time")     # 發佈會時間
    create_time = models.DateTimeField(auto_now=True)   # 建立時間(自動獲取當前時間)

    def __str__(self): return self.name # 嘉賓表
class Guest(models.Model): event = models.ForeignKey(Event)                    # 關聯發佈會id
    realname = models.CharField(max_length=64)          # 姓名
    phone = models.CharField(max_length=16)             # 手機號
    email = models.EmailField()                         # 郵箱
    sign = models.BooleanField()                        # 簽到狀態
    create_time = models.DateTimeField(auto_now=True)   # 建立時間(自動獲取當前時間)
def __str__(self): return self.realname
class Meta: unique_together = ("event","phone") 

模型建立好後,進行數據遷移:shell

打開終端執行:數據庫

test:guest zhan$ python manage.py makemigrations sign Migrations for 'sign': sign/migrations/0001_initial.py: - Create model Event - Create model Guest test:guest zhan$ python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions, sign Running migrations: Applying sign.0001_initial... OK

  sign/migrations/下會生成0001_initial.py文件:django

 

2、admin後臺管理           返回目錄

首先,在sign/admin.py文件中寫入:session

from django.contrib import admin from sign.models import Event,Guest # Register your models here.
# 這些代碼通知Admin管理工具爲這些模塊提供界面
admin.site.register(Event) admin.site.register(Guest)

以下圖:框架

登陸Admin後臺系統:http://127.0.0.1:8000/admin/ 工具

添加發佈會: 

列表顯示一列發佈會名字,是由於本身定義了__str__():裏面的name

若是想顯示所有的列表字段,則在 sign/admin.py中繼續添加:

from django.contrib import admin from sign.models import Event,Guest # Register your models here.
# 添加兩個方法,把字段值放在list_display中
class EventAdmin(admin.ModelAdmin): list_display = ["id","name","limit","status","address","start_time","create_time"] class GuestAdmin(admin.ModelAdmin): list_display = ["event","realname","phone","email","sign","create_time"] # 這些代碼通知Admin管理工具爲這些模塊提供界面
admin.site.register(Event,EventAdmin)  # 並添加class進來 admin.site.register(Guest,GuestAdmin)  

還能夠添加【搜索欄、過濾器】,在sign/admin.py中繼續添加:

from django.contrib import admin from sign.models import Event,Guest # Register your models here.

class EventAdmin(admin.ModelAdmin): list_display = ["id","name","limit","status","address","start_time","create_time"] search_fields = ["name"]    # 搜索欄
    list_filter = ["status"]    # 過濾器

class GuestAdmin(admin.ModelAdmin): list_display = ["event","realname","phone","email","sign","create_time"] search_fields = ["realname","phone"]    # 搜索欄
    list_filter = ["sign"]                  # 過濾器


# 這些代碼通知Admin管理工具爲這些模塊提供界面
admin.site.register(Event,EventAdmin) admin.site.register(Guest,GuestAdmin)

search_fields:用於建立搜索欄,能夠設置匹配多個關鍵字。

list_filter:用於建立字段過濾器。

 

3、基本數據訪問(SQLite數據庫)     返回目錄

下面咱們經過Django自帶的SQLite操做數據庫,如何經過數據庫進行操做呢,須要命令行運行manage.py的shell命令

python manage.py shell

一、插入語句

# 準備條件
>>> from sign.models import Event,Guest >>> from datetime import datetime >>> Event.objects.all() <QuerySet [<Event: 小米發佈會>]> >>> Guest.objects.all() <QuerySet [<Guest: zc>]>

①第一種插入語句:建立和保存

insert_e1 = Event(id='2', name='魅族發佈會', limit='1000', status=True, address='天津梅江會展', start_time=datetime(2018,10,15,12,0,0)) insert_e1.save()

②第二種插入語句:直接建立

Event.objects.create(id='2', name='魅族發佈會', limit='1000', status=True, address='天津梅江會展', start_time=datetime(2018,10,15,12,0,0))

Guest.objects.create(realname='owen',
phone= '136',
email='136@qq.com',
sign=False,
event_id='2')

可是會提示警告信息:

1430: RuntimeWarning: DateTimeField Event.start_time received a naive datetime (2018-10-15 12:00:00) while time zone support is active. RuntimeWarning)

UTC問題,能夠忽略此問題,guest/settings.py中,設置USE_TZ = False。

二、查詢語句

(1)精確查詢

address做爲查詢條件,查詢name

>>> e1 = Event.objects.get(address = '天津梅江會展') >>> e1.name '魅族發佈會' 
# 或者

>>> Event.objects.get(address = '天津梅江會展').name
'魅族發佈會'
>>>

 

相對應的Guest表:

>>> g1 = Guest.objects.get(realname__contains='ow') >>> g1.event <Event: 魅族發佈會>
>>> g1.event.name '魅族發佈會' >>> g1.event.address '天津梅江會展' >>>

(2)模糊查詢

只想查詢關鍵字

filter()方法是從數據庫中取得匹配結果,返回的是列表;name與contains雙下劃線鏈接,contains相似於LIKE語句。

>>> Event.objects.filter(name__contains='發佈會') <QuerySet [<Event: 小米發佈會>, <Event: 魅族發佈會>]>
>>>

(3)刪除數據

注:我寫的是模糊查詢刪除,最好是精確刪除。

>>> g1 = Guest.objects.get(realname__contains='ow') >>> g1.delete() (1, {'sign.Guest': 1}) >>> 

# 或者
>>> Guest.objects.get(realname__contains='ow').delete() (1, {'sign.Guest': 1}) >>>

(4)更新數據

>>> g1 = Guest.objects.get(realname__contains='ow') >>> g1.realname='owen02' >>> g1.save() >>> 

# 或者
 Guest.objects.select_for_update().filter(realname__contains='ow').update(realname='owen') 1

4、Django配置MySQL         返回目錄

雖然SQLite數據庫能夠操做數據,可是不適用於大型項目,下面來介紹MySQL數據庫在Django中的操做。

一、安裝Mysql數據庫

參考個人另外一篇文章:《【Mac系統 + Mysql】之安裝Mysql數據庫

二、MySQL數據庫基本操做

數據庫操做:

# 進入mysql
mysql -u root -p
# 查看數據庫 show databases; # 建立數據庫 create database if not exists guest; # 進入guest數據庫 use guest; # 查看數據庫的表 show tables; # 建立表 create table if not exists sign_guest( id int unsigned auto_increment, realname varchar(100)not null, phone varchar(16) not null, email VARCHAR(20) UNIQUE, # UNIQUE:不可重複,只有null是能夠重複 sign varchar(5), create_time date, primary key(id,phone) )charset=utf8; # 查看錶屬性 desc sign_guest; # 插入數據 insert into sign_guest(realname,phone,email,sign,create_time)values
('zc','16612345678','123@qq.com','1',now())

三、安裝pymysql

安裝命令:

pip install pymysql

具體操做可參考個人文章:《【Python + Mysql】之用pymysql庫鏈接Mysql數據庫並進行增刪改查操做

在此忽略......

四、在Django中配置MySQL

修改guest/settings.py下的DATABASES

DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql',   # 驅動
        'HOST': '127.0.0.1',                    # 主機地址
        'PORT': '3306',                         # 端口號
        'NAME': 'guest',                        # 數據庫
        'USER': 'root',                         # 登陸用戶名
        'PASSWORD': '1234567',                  # 登陸密碼
        'OPTIONS': { 'init_command': "SET sql_mode='STRICT_TRANS_TABLES'", }, } }

在guest項目中輸入命令:

test:guest zhan$ python manage.py migrate

可是報錯:

django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named 'MySQLdb'

緣由爲沒有MySQLdb驅動,解決辦法以下:

在.../guest/__init__.py中添加代碼:

import pymysql pymysql.install_as_MySQLdb()

而後再執行命令:

python manage.py migrate

可是,會提示錯誤,若是沒有問題跳過此段落:

......

Applying auth.0006_require_contenttypes_0002... OK

Applying auth.0007_alter_validators_add_error_messages... OK

Applying auth.0008_alter_user_username_max_length... OK

Applying sessions.0001_initial... OK

Applying sign.0001_initial...Traceback (most recent call last):

...

...

...

pymysql.err.InternalError: (1050, "Table 'sign_guest' already exists")

 

緣由爲我在上面寫mysql基本數據庫操做時候,本身建立了sign_guest表,因此最好刪除guest數據庫,從新再執行一遍命令。

終端進入數據庫,具體操做不描述,上面基本操做介紹過。

# 刪除數據庫
drop database guest; # 建立數據庫
create database guest;

 

再執行命令:

python manage.py migrate

正確顯示以下:

Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions, sign Running migrations: Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... 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 auth.0007_alter_validators_add_error_messages... OK Applying auth.0008_alter_user_username_max_length... OK Applying sessions.0001_initial... OK Applying sign.0001_initial... OK

由於更換了數據庫,因此裏面的Admin超級管理員帳號也須要從新建立。

而後再終端輸入命令:

python manage.py createsuperuser
Username (leave blank to use 'zhan'): admin Email address: xxx@xxx.com Password: Password (again): Superuser created successfully.

 

至此,Django的模型建立完畢,下一篇介紹Django模板 

相關文章
相關標籤/搜索