1. 程式人生 > >Django 的學習(1) 從建立到數據庫操作

Django 的學習(1) 從建立到數據庫操作

there AR 報錯 tom capture base 出了 手動 模型

基本是翻譯官方教程

技術分享圖片
django-admin startproject mysite
創建工程的命令

來看一下django的結構圖
manage.py 和工程交互的多種方式
inner mysilte 是需要import的包
init.py是定義這裏是py 的package
settings.py 設置
urls.py 聲明?
wsgi.py Web Server Gateway Interface

python manger.py migrate 大概是配置吧
然後就是
python manage.py runserver 但是不行(估計是設置的問題)
然後
python manage.py runserver 0.0.0.0:8000
就可以訪問了

web app 可以再在python path的任意位置
在這裏我們創建在manage.py的同級目錄下
創建
$ python manage.py startapp polls
編輯views.py文件
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello, world. You‘re at the polls index.")
建立了最簡單的views之後,需要將它映射到URL 中

在同一目錄下建立
urls.py
編輯

from django.conf.urls import url

from . import views

urlpatterns = [
    url(r‘^$‘, views.index, name=‘index‘),
]

然後在全局的url中指向polls.urls

mysite/urls.py

from django.conf.urls import include, url
from django.contrib import admin

urlpatterns = [
    url(r‘^polls/‘, include(‘polls.urls‘)),
    url(r‘^admin/‘, admin.site.urls),
]

註意^符號,因為include 函數不吃$
使用include 可以將URL放在各個位置沒有必要放在一塊
值得一提的是唯一的例外是
admin.site.urls

我們是用的url函數建立聯系的將
view.py 映射到URL上去
url函數:
參數:
regex 字符串
用於匹配的字符串

view
如果匹配到了regex就會調用這個指定的view function
用httpRequest作為第一個參數,和被匹配到的字符作為其他參數
If the regex uses simple captures, values are passed as positional arguments; if it uses named captures, values are passed as keyword arguments. We’ll give an example of this in a bit.
看不懂,不過後面會有例子

argument:kwargs
在字典裏面的,tutoril裏面不介紹

name
一個字符串
為URL指定一個無歧義的名字,這樣可以再全局上對URL patterns做修改

part2 鏈接數據庫

配置數據庫
以前安裝了mysql
現在在安裝了
安裝mysqlclient 時報錯 OSError: mysql_config not found
原因是沒有安裝:libmysqlclient-dev
sudo apt-get install libmysqlclient-dev
找到mysql_config文件的路徑
sudo updatedb
locate mysql_config
mysql_config的位置為:/usr/bin/mysql_config
沒有按照http://blog.163.com/zhu329599788@126/blog/static/6669335020161260025544/ 的源碼包安裝
只是直接Pip安裝了

配置文件 setting.py
主要是Database的部分要加上一些參數

我又作死去改了mysql的端口,從默認的3306改成6666
主要是 /etc/mysql/my/cnf 裏面的兩處port設置

然後再運行 service mysql start 就可以了

運行服務器的時候要先
python manage.py migration

然後在setting.py 中添加了installed_app 中 “polls”
python manage.py migration其實就是將setting.py中的配置生效的過程

然後修改polls 下的models.py大概是 數據庫模型的意思吧
from django.db import models

class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField(‘date published‘)

class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
每一個class 都是django.db.models.Model 的子類
稱為 model

每一個model 下的variables(models 下的Field子類) 對應著數據庫中的一項
You’ll use this value in your Python code, and your database will use it as the column name.
每一個model 對應著數據庫中的一個table
但是要想他們生效必須先
python manage.py makemigrations

python manage.py migrate
每一個 Field 類型的變量可以指定名字,
有些則需要參數,比如CharField 需要一個 maxlength
這個參數還將用於validation 中
Field 還可以有默認值

我們是用ForeignKey 定義了一個關系
每一個Choic 都被聯系到一個Question上了
Django支持數據庫的多種鏈接方式
多對多,一對一,多對一
在Django中app是獨立的,每一個app可以被多個projetc使用

在Django中 INSTALLED_APPS 中最好不要直接寫上“polls”
可以寫上
"polls.apps.PollsConfig"
這樣是吧polls的配置文件轉移到了polls內,非常方便
在apps.py內有一個PollsConig類
有一個name 的方法返回polls
作用和上訴的東西應該是一樣的
python manage.py makemigrations polls

By running makemigrations, you’re telling Django that you’ve made some changes to your models (in this case, you’ve made new ones) and that you’d like the changes to be stored as a migration.

makemigrations 只是做出了改變

這個文件生成在
polls/migrations/0001_initial.py.
這個文件可以手工編輯

Migrations are how Django stores changes to your models (and thus your database schema) - they’re just files on disk. You can read the migration for your new model if you like; it’s the file polls/migrations/0001_initial.py. Don’t worry, you’re not expected to read them every time Django makes one, but they’re designed to be human-editable in case you want to manually tweak how Django changes things.

There’s a command that will run the migrations for you and manage your database schema automatically - that’s called migrate, and we’ll come to it in a moment - but first, let’s see what SQL that migration would run. The sqlmigrate command takes migration names and returns their SQL:

python manage.py sqlmigrate polls 0001
這個命令可以展示migrate的細節
轉化成了sql 語言來操作數據庫

轉化的結果由具體使用的數據庫而定(我猜engine 就是做這個事情的)

Table 的名字由 app的名字和 model的名字混合而成

primary keys(id )是被自動添加上去的(可以手動修改)

慣例,django添加_id 對應 Forenognkey file name 上取(可以重寫)

database-specific filed 取決於你的數據庫
It’s tailored to the database you’re using, so database-specific field types such as auto_increment (MySQL), serial (PostgreSQL), or integer primary key autoincrement (SQLite) are handled for you automatically. Same goes for the quoting of field names – e.g., using double quotes or single quotes.

The sqlmigrate 並不真的去做migrate只是輸出一下sql語句讓你心裏有個數

命令python manage.py check
是檢查工程中有沒有不問題(不實際的做 migrate 或 database)

小結

更改數據庫文件的三步驟
Change your models (in models.py).
Run python manage.py makemigrations to create migrations for those changes
Run python manage.py migrate to apply those changes to the database.
之所以要這麽設計是為了,讓多人開發變得方便
Read the django-admin documentation for full information on what the manage.py utility can do.

和api一起玩

python manage.py

不簡單的調用python,
因為manage.py 設置了
DJANGO_SETTINGS_MODULE 環境變量。
可以得到 sfsite/setings.py文件的路徑

如果不想這麽做也可以
只需要設計環境變量
DJANGO_SETTINGS_MODULE environment variable to mysite.settings

必須在同一級下的manage.py
因為要讓import sfsite 有效

進入shell後就可以操作了
···
import django
django.setup()
q = Question(question_text="What‘s new?", pub_date=timezone.now())

Save the object into the database. You have to call save() explicitly.

q.save()

Now it has an ID. Note that this might say "1L" instead of "1", depending

on which database you‘re using. That‘s no biggie; it just means your

database backend prefers to return integers as Python long integer

objects.

q.id
1

Access model field values via Python attributes.

q.question_text
"What‘s new?"
q.pub_date
datetime.datetime(2012, 2, 26, 13, 0, 0, 775217, tzinfo=

Change values by changing the attributes, then calling save().

q.question_text = "What‘s up?"
q.save()

objects.all() displays all the questions in the database.

Question.objects.all()
<QuerySet [

重新打卡shell
利用django提供的api對數據庫進行操作

Question.objects.all() 查看所有
Question.objects.filter(id=1) 過濾
Question.objects.filter(question_text__startswith=‘What‘)
註意這個表示法,方法用__兩個下劃線表示

>>> from django.utils import timezone
>>> current_year = timezone.now().year
>>> Question.objects.get(pub_date__year=current_year)
<Question: What‘s up?>

# Request an ID that doesn‘t exist, this will raise an exception.
>>> Question.objects.get(id=2)
Traceback (most recent call last):
    ...
DoesNotExist: Question matching query does not exist.

# Lookup by a primary key is the most common case, so Django provides a
# shortcut for primary-key exact lookups.
# The following is identical to Question.objects.get(id=1).
>>> Question.objects.get(pk=1)
<Question: What‘s up?>

# Make sure our custom method worked.
>>> q = Question.objects.get(pk=1)
>>> q.was_published_recently()
True

# Give the Question a couple of Choices. The create call constructs a new
# Choice object, does the INSERT statement, adds the choice to the set
# of available choices and returns the new Choice object. Django creates
# a set to hold the "other side" of a ForeignKey relation
# (e.g. a question‘s choice) which can be accessed via the API.
>>> q = Question.objects.get(pk=1)

# Display any choices from the related object set -- none so far.
>>> q.choice_set.all()
<QuerySet []>

# Create three choices.
>>> q.choice_set.create(choice_text=‘Not much‘, votes=0)
<Choice: Not much>
>>> q.choice_set.create(choice_text=‘The sky‘, votes=0)
<Choice: The sky>
>>> c = q.choice_set.create(choice_text=‘Just hacking again‘, votes=0)

# Choice objects have API access to their related Question objects.
>>> c.question
<Question: What‘s up?>

# And vice versa: Question objects get access to Choice objects.
>>> q.choice_set.all()
<QuerySet [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]>
>>> q.choice_set.count()
3

# The API automatically follows relationships as far as you need.
# Use double underscores to separate relationships.
# This works as many levels deep as you want; there‘s no limit.
# Find all Choices for any question whose pub_date is in this year
# (reusing the ‘current_year‘ variable we created above).
>>> Choice.objects.filter(question__pub_date__year=current_year)
<QuerySet [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]>

# Let‘s delete one of the choices. Use delete() for that.
>>> c = q.choice_set.filter(choice_text__startswith=‘Just hacking‘)
>>> c.delete()

這樣就可以對數據庫進行操作
本質上是對models.py 裏面的類的映射

Django 的學習(1) 從建立到數據庫操作