標籤:com 隨機 not err 儲存資料 whether datetime 進入 client
python版本 3.6.1
http://www.zmrenwu.com/category/django-blog-tutorial/
1.mysql資料庫 設定
安裝 pip install pymysql
安裝 pip install mysqlclient
設定 mysql串連的參數
settings.py
DATABASES = {
‘default‘: {
‘ENGINE‘: ‘django.db.backends.mysql‘,
‘NAME‘: "py3django",
‘USER‘: "root",
‘PASSWORD‘: "123456",
‘HOST‘: "127.0.0.1",
}
}
2 常用指令
啟動服務 runserver
遷移資料庫
makemigrations
migrate
建立使用者 createsuperuser
根據提示 輸入使用者,輸入郵箱,輸入密碼
進入shell介面 :shell
3.models.py 的操作
https://docs.djangoproject.com/en/1.10/ref/models/querysets/
擷取所有資料 類對象.objects.all()
擷取過濾的資料,進返回一條資料,get方法
類對象.objects.get(name=‘category test‘)
Category.objects.get(name=‘category test‘) 的含義是從資料庫中取出 name 的值為 category test 的分類記錄。
確保資料庫中只有一條值為 category test 的記錄,否則 get 方法將返回一個 MultipleObjectsReturned 異常。
儲存資料, xx=類對象.objects.all()
xx.save() #增 改
xx.delete() #刪除
https://docs.djangoproject.com/en/1.10/ref/models/querysets/
QuerySet
4.models類對象資料顯示最佳化
為了讓顯示出來的資料更加人性化一點,為模型分別增加一個 __str__ 方法:
def __str__(self):
return self.name
定義好 __str__ 方法後,解譯器顯示的內容將會是 __str__ 方法返回的內容。
注意:python_2_unicode_compatible 裝飾器用於相容 Python2
(from django.utils.six import python_2_unicode_compatible)
# python_2_unicode_compatible 裝飾器用於相容 Python2
@python_2_unicode_compatible
class Category(models.Model):
...
def __str__(self):
return self.name
5.查詢 QuerySet API
https://docs.djangoproject.com/en/1.10/ref/models/querysets/
filter(**kwargs) :返回包含所有合格 QuerySet,對應的參數,須為查詢的表中的欄位
Returns a new QuerySet containing objects that match the given lookup parameters.
The lookup parameters (**kwargs) should be in the format described in Field lookups below.
Multiple parameters are joined via AND in the underlying SQL statement.
exclude(**kwargs) :過濾條件 不包括(即 not in )
This example excludes all entries whose pub_date is later than 2005-1-3 AND whose headline is “Hello”:
Entry.objects.exclude(pub_date__gt=datetime.date(2005, 1, 3), headline=‘Hello‘)
SQL語句:SELECT ...
WHERE NOT (pub_date > ‘2005-1-3‘ AND headline = ‘Hello‘)
或者
SELECT ...
WHERE NOT pub_date > ‘2005-1-3‘
AND NOT headline = ‘Hello‘
order_by(*fields):排序欄位
By default, results returned by a QuerySet are ordered
by the ordering tuple given by the ordering option in the model’s Meta.
You can override this on a per-QuerySet basis by using the order_by method
for example:
Entry.objects.filter(pub_date__year=2005).order_by(‘-pub_date‘, ‘headline‘)
解釋: The result above will be ordered by pub_date descending,
then by headline ascending.
The negative sign in front of "-pub_date" indicates descending order.
Ascending order is implied. To order randomly, use "?", like so:
隨機排序,使用‘?’ : Entry.objects.order_by(‘?‘)
distinct(*fields) :去重複方法
values(*fields) :擷取對應欄位的的values列表
for example:
>>> Blog.objects.values()
<QuerySet [{‘id‘: 1, ‘name‘: ‘Beatles Blog‘, ‘tagline‘: ‘All the latest Beatles news.‘}]>
>>> Blog.objects.values(‘id‘, ‘name‘)
<QuerySet [{‘id‘: 1, ‘name‘: ‘Beatles Blog‘}]>
all()
Returns a copy of the current QuerySet (or QuerySet subclass).
This can be useful in situations where you might want to
pass in either a model manager or a QuerySet and do further
filtering on the result. After calling all() on either object,
you’ll definitely have a QuerySet to work with.
Methods that do not return QuerySets
get(**kwargs): 查詢結果多條時,報錯
Returns the object matching the given lookup parameters,
which should be in the format described in Field lookups.
get() raises MultipleObjectsReturned if more than one object was found.
The MultipleObjectsReturned exception is an attribute of the model class.
count():統計個數
Returns an integer representing the number of objects in the database matching the QuerySet.
The count() method never raises exceptions.
for example:
# Returns the total number of entries in the database.
Entry.objects.count()
# Returns the number of entries whose headline contains ‘Lennon‘
Entry.objects.filter(headline__contains=‘Lennon‘).count()
latest(field_name=None)
Returns the latest object in the table,
by date, using the field_name provided as the date field.
This example returns the latest Entry in the table, according to the pub_date field:
Entry.objects.latest(‘pub_date‘)
If your model’s Meta specifies get_latest_by,
you can leave off the field_name argument to earliest() or latest().
Django will use the field specified in get_latest_by by default.
Like get(), earliest() and latest() raise DoesNotExist
if there is no object with the given parameters.
Note that earliest() and latest() exist purely for convenience and readability.
earliest()
first()
last()
exists():
Returns True if the QuerySet contains any results, and False if not.
This tries to perform the query in the simplest and fastest way possible,
but it does execute nearly the same query as a normal QuerySet query.
exists() is useful for searches relating to both object membership in a QuerySet and to the existence of any objects in a QuerySet,
particularly in the context of a large QuerySet.
The most efficient method of finding whether a model with a unique field (e.g. primary_key) is a member of a QuerySet is:
entry = Entry.objects.get(pk=123)
if some_queryset.filter(pk=entry.pk).exists():
print("Entry contained in queryset")
Which will be faster than the following which requires evaluating and iterating through the entire queryset:
if entry in some_queryset:
print("Entry contained in QuerySet")
update()
delete()
python 項目隨筆-2