frist Django app— 2、 Model和管理界面

Django是符合MVC架構的,這裏現學習M—Model,並且Django自帶了一個管理model(數據庫)的界面,因此一併學習。python

Database 配置

編輯Django的配置文件settings.py進行配置mysql

添加polls app,修改後以下web

INSTALLED_APPS = [
    'django.contrib.admin',      # 管理界面
    'django.contrib.auth',       # 認證系統
    'django.contrib.contenttypes',  # 框架的content type
    'django.contrib.sessions',     # session framework
    'django.contrib.messages',     # messages framework
    'django.contrib.staticfiles',   # 管理靜態文件的framework
    'polls.apps.PollsConfig',      # 咱們本身的app
]

最後一行位新添加的,表示新增一個app,類polls.apps.PoolsConfig定義了app,名稱爲「polls」(能夠打開這個類看到)。sql

還能夠看到不少其餘的app,咱們以前說過,一個project能夠有多個app,一個app能夠屬於多個project,這個的實現方式就是這樣,每一個app都位於不一樣的包下面,若是一個project想包含一個app,只須要把這個app的包的配置寫在這兒就能夠了。shell

接下來配置數據庫,修改完以後以下數據庫

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': 'polls.db',
    }
}

Django支持大多數主流的數據庫,包括postgresql,mysql,sqlite等,這裏爲了簡單就直接用sqlite,若是使用mysql應該配置成以下(其餘相似)django

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'django',
        'USER': 'root',
        'PASSWORD': 'root',
        'HOST': 'localhost',
        'PORT': '3306',
    }
}

數據庫至此配置完成,接下來就是建立modelsession

建立model

編輯mysite/polls/models.py架構

from __future__ import unicode_literals

from django.db import models

# Create your models here.
class Question(models.Model):
   # CharField:字段是字符串類型,有一個必要參數——字符串長度 question_text
= models.CharField(max_length=200)
   # DateField:字段是日期類型 publ_date
= models.DateField('date published')

    def __unicode__(self):
        return self.question_text
class Choice(models.Model):
   # question做爲choice的外鍵,這裏是多對一關係,刪除的時候進行級聯,Django還支持:many-to-one, many-to-many, and one-to-one. question
= models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0)

    def __unicode__(self):
        return self.choice_text

每一個model繼承自models.Model,會繼承一些經常使用的操做方法。每一個class對應的屬性都對應數據庫中表中的字段——這也就是ORMapp

生成數據庫表結構

# 告訴Django model改變了,而且保存爲一個migration
python manage.py makemigrations

運行該命令,輸出以下內容,並在pools/migrations下生成0001_initial.py

Migrations for 'polls':
  0001_initial.py:
    - Create model Choice
    - Create model Question
    - Add field question to choice

咱們能夠看看Django根據這個migration會怎麼生成表結構運行

# 0001 爲以前生成的0001_initial.py的前綴,表示第一個版本的migration
python manage.py sqlmigrate polls 0001

輸出

BEGIN;
--
-- Create model Choice
--
CREATE TABLE "polls_choice" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "choice_text" varchar(200) NOT NULL, "votes" integer NOT NULL);
--
-- Create model Question
--
CREATE TABLE "polls_question" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "question_test" varchar(200) NOT NULL, "publ_date" date NOT NULL);
--
-- Add field question to choice
--
ALTER TABLE "polls_choice" RENAME TO "polls_choice__old";
CREATE TABLE "polls_choice" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "choice_text" varchar(200) NOT NULL, "votes" integer NOT NULL, "question_id" integer NOT NULL REFERENCES "polls_question" ("id"));
INSERT INTO "polls_choice" ("choice_text", "votes", "id", "question_id") SELECT "choice_text", "votes", "id", NULL FROM "polls_choice__old";
DROP TABLE "polls_choice__old";
CREATE INDEX "polls_choice_7aa0f6ee" ON "polls_choice" ("question_id");

COMMIT;
View Code

Django會運行上面這些語句來生成數據庫表結構,咱們能夠看到生成兩張表分別對應兩個model,給question這張表添加一個外鍵。

如今咱們能夠生成數據庫表結構了,這個命令就是將上面生成的migration應用到數據庫

python manage.py migrate

輸出

Operations to perform:
  Apply all migrations: admin, contenttypes, polls, auth, sessions
Running migrations:
  Rendering model states... DONE
  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 polls.0001_initial... OK
  Applying sessions.0001_initial... OK
View Code

到這兒,數據庫表結構生成完畢,咱們可使用sqlite3查看生成的表結構

sqlite3 polls.db
#如下爲輸出內容
SQLite version 3.8.7.1 2014-10-29 13:59:56
Enter ".help" for usage hints.
sqlite> .tables
auth_group                  django_admin_log          
auth_group_permissions      django_content_type       
auth_permission             django_migrations         
auth_user                   django_session            
auth_user_groups            polls_choice              
auth_user_user_permissions  polls_question       
View Code

 

使用API操做model

# 這裏用的是ipython,進入django命令行
python manage.py shell
Python 2.7.9 (default, Mar  1 2015, 18:22:53) 
Type "copyright", "credits" or "license" for more information.

IPython 2.3.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.
# 導入model
In [2]: from polls.models import Choice, Question
# 查看全部的question對象
In [3]: Question.objects.all()
Out[3]: [<Question: what`s up?>]
# 獲取id爲0的對象,沒有id爲0的對象,因此會報錯
In [5]: Question.objects.get(id=0)
---------------------------------------------------------------------------
DoesNotExist                              Traceback (most recent call last)
<ipython-input-5-bd4c3a1273f2> in <module>()
----> 1 Question.objects.get(id=0)

/usr/local/lib/python2.7/dist-packages/Django-1.9.7-py2.7.egg/django/db/models/manager.pyc in manager_method(self, *args, **kwargs)
    120         def create_method(name, method):
    121             def manager_method(self, *args, **kwargs):
--> 122                 return getattr(self.get_queryset(), name)(*args, **kwargs)
    123             manager_method.__name__ = method.__name__
    124             manager_method.__doc__ = method.__doc__

/usr/local/lib/python2.7/dist-packages/Django-1.9.7-py2.7.egg/django/db/models/query.pyc in get(self, *args, **kwargs)
    385             raise self.model.DoesNotExist(
    386                 "%s matching query does not exist." %
--> 387                 self.model._meta.object_name
    388             )
    389         raise self.model.MultipleObjectsReturned(

DoesNotExist: Question matching query does not exist.
# 獲取id爲1的對象
In [6]: Question.objects.get(id=1)
Out[6]: <Question: what`s up?>

In [7]: q = Question.objects.get(id=1)
# 刪除該對象
In [8]: q.delete()
Out[8]: (4, {u'polls.Choice': 3, u'polls.Question': 1})
# 查看發現已經刪除
In [9]: Question.objects.all()
Out[9]: []

In [11]: from django.utils import timezone
# 新建一個對象
In [13]:  q = Question(question_text="What's new?", publ_date=timezone.now())
# 保存到數據庫
In [15]: q.save()
# 保存到數據庫以後Django自動生成了id,只有在save以後纔有
In [16]: q.id
Out[16]: 2
# 查看字段值
In [17]: q.question_text
Out[17]: "What's new?" 

In [18]: q.publ_date
Out[18]: datetime.datetime(2016, 7, 10, 13, 12, 40, 146050, tzinfo=<UTC>)

In [19]: q.question_text = "What's up?"

In [20]: q.save()

In [22]: q
Out[22]: <Question: What's up?>

In [23]: Question.objects.all()
Out[23]: [<Question: What's up?>]

In [24]:  Question.objects.filter(id=1)
Out[24]: []
# 使用filter查詢
In [25]:  Question.objects.filter(id=2)
Out[25]: [<Question: What's up?>]

In [26]: Question.objects.filter(question_text__startswith='What')
Out[26]: [<Question: What's up?>]

In [29]:  Question.objects.get(publ_date__year=timezone.now().year)
Out[29]: <Question: What's up?>
# 查看question關聯的choice
In [30]: q.choice_set.all()
Out[30]: []
# 新建一個choice關聯到question
In [31]: q.choice_set.create(choice_text='Not much', votes=0)
Out[31]: <Choice: Not much>

In [32]: q.choice_set.create(choice_text='The sky', votes=0)
Out[32]: <Choice: The sky>

In [33]: c = q.choice_set.create(choice_text='Just hacking again', votes=0)
# 查看choice對應的question
In [34]: c.question
Out[34]: <Question: What's up?>

In [35]: q.choice_set.all()
Out[35]: [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]

In [36]: q.choice_set.count()
Out[36]: 3
View Code

Django提供了不少API來操做model,包括新建、更新、刪除、關聯、從一個對象查詢關聯的對象等等,除此以外Django還提供了web界面對model進行管理。

Django Admin

使用如下命令依次輸入用戶名、郵箱(注意郵箱)、密碼(8位以上的字母數字組成)

python manage.py createsuperuser

訪問http://127.0.0.1:8000/admin/登錄,能夠看到管理界面,可是如今並無mode,接下來註冊model

編輯polls/admin.py

from django.contrib import admin
from polls.models import Choice, Question

# Register your models here.
admin.site.register(Choice)
admin.site.register(Question)

再次登錄就能夠看到model:Choice,Question,能夠在界面上增刪改查,so easy

 


代碼位置

http://pan.baidu.com/s/1dFshtXB

相關文章
相關標籤/搜索