django學習-數據庫操作接口API--(CRUD)


初試API(數據庫操作接口CRUD)

現在我們進入交互式python命令行,嘗試一下django為你創建的各種API,通過以下命令打開python命令行:

py -3 manage.py shell進入python命令行

 

D:\django\mysite>py -3 manage.py shell

Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD64)] on win32

Type "help", "copyright", "credits" or "license" for more information.

(InteractiveConsole)

 

我們使用這個命令而不是簡單的使用”python”是因為manage.py會設置DJANGO_SETTINGS_MODULE環境變量,這個變量會讓django根據mysite/settings.py文件來設置python包的導入路徑

 

當我們成功進入命令行后,來試試database API:

命令行下初始化模型類並查詢:

#導入模型類

>>> from polls.models import Choice, Question

#查詢模型類數據

>>> Question.objects.all()

<QuerySet []>

#創建Question類對象

#在django的默認配置文件中,時區time zones已經被啟用

#pub_date字段需要待時區信息(tzinfo)的時間,所以要使用timezone.now(),而不是

#datetiem.datetime.now(),這方便於進行時區的切換后時間的展示

>>> from django.utils import timezone

>>> q = Question(question_text="What's new?", pub_date=timezone.now())

>>> q.save()

>>> q.id

1

>>> q.question_text

"What's new?"

>>> q.pub_date

datetime.datetime(2019, 10, 4, 10, 4, 45, 113879, tzinfo=<UTC>)

>>> q.pub_text = "What's up?"

>>> q.save()

>>> Question.objects.all()

<QuerySet [<Question: Question object (1)>]>

>>> 

 

<Question: Question object (1)>對於我們了解這個對象的細節沒什么幫助。讓我們通過編輯question模型的代碼(polls/models.py中)來修復這個問題。

給Question和Choice增加__str__()方法。

 

給模型添加__str__()方法

polls/models.py:

 

from django.db import models

# Create your models here.

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

    def __str__(self):
        return self.question_text

class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

    def __str__(self):
        return self.choice_text

 

給模型增加__str__()方法很重要,這不僅僅能給你在命令行里使用帶來方便,django自動生成的admin里也使用這個方法表示對象。

 

注意:這些都是常規的python方法,讓我們添加一個自定義的方法,進行演示:

from django.db import models
from django.utils import timezone
import  datetime
# Create your models here.

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

    def __str__(self):
        return self.question_text

    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)

新加入的import datetime和from django.utils import timezone分別導入了python的標准datetime模塊和django中和時區相關的django.utils.timezone工具模塊。

 

保存文件然后通過python manage.py shell命令再次打開python交互命令行:

再次查詢

>>> from polls.models import Choice, Question

#查詢Question類所有對象,查看__str__()是否起作用

Question.objects.all()查詢所有Question對象

>>> Question.objects.all()

<QuerySet [<Question: What's new?>]>

 

Question.objects.filter(id=1)查詢id為1的

>>> Question.objects.filter(id=1)

<QuerySet [<Question: What's new?>]>

 

Question.objects.filter(question_text__startswith='What')查詢前綴是What的

#startswith前面是兩個下划線

>>> Question.objects.filter(question_text__startswith='What')

<QuerySet [<Question: What's new?>]>

 

from django.utils import timezone引入時區對象   

>>> from django.utils import timezone

>>> current_year = timezone.now().year

>>> current_year

2019

 

Question.objects.get(pub_date__year=current_year)

#查找發布時間是今年的問題

>>> Question.objects.get(pub_date__year=current_year)

<Question: What's new?>

 

Question.objects.get(id=2)按id查詢

#查找沒有的會報錯

>>> Question.objects.get(id=2)

Traceback (most recent call last):

 …

polls.models.Question.DoesNotExist: Question matching query does not exist.

 

django提供主鍵查詢的縮寫格式pk=1

Question.objects.get(pk=1)

#

>>> Question.objects.get(pk=1)

<Question: What's new?>

>>> q = Question.objects.get(pk=1)

q.was_published_recently()調用實例方法

 

>>> q.was_published_recently()

True

q.choice_set.create()給question對象添加choice關系對象

我們給question對象添加幾個Choice類的關系對象。

q.choice_set.create()中的create方法構造一個新的Choice實例對象,操作insert語句,把Choice實例對象添加到可用的choice對象的集合中,並返回新的Choice實例對象

django會創建一個集合,這個集合用來存儲外鍵關系的”另一側”的對象,例如question對象的關系的另一側:choice(選項),之后就可以通過數據庫操作API訪問到這個寫關系對象

q.choice_set.all()查看question的choice選項,用choice_set返回QuerySet對象,可以繼續操作查詢

#開始時choice關系對象是空

>>> q.choice_set.all()

<QuerySet []>

創建三個choice關系對象

>>> 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)

c.question查看choice對象的question關系對象

>>> c.question

<Question: What's new?>

#再次查詢question對象的choice關系對象

>>> q.choice_set.all()

<QuerySet [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]>

q.choice_set.count()查看關系對象的數量

>>> q.choice_set.count()

3

API會按照你的需要自動的處理關聯關系,使用雙下划線分隔關系,你想要多少層就可以有多少層,沒有限制

下面的例子是找到選項(choice)對應的所有問題,篩選其中發布日期是在今年的所有對象

重用在上面建的current_year變量

 

c.delete()刪除對象

Choice.objects.filter(question__pub_date__year=current_year)

>>> Choice.objects.filter(question__pub_date__year=current_year)

<QuerySet [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]>

>>> c = q.choice_set.filter(choice_text__startswith='Just hacking')

>>> c

<QuerySet [<Choice: Just hacking again>]>

>>> c.delete()

(1, {'polls.Choice': 1})

>>> c

<QuerySet []>

>>> q.choice_set.all()

<QuerySet [<Choice: Not much>, <Choice: The sky>]>

>>> Choice.objects.all()

<QuerySet [<Choice: Not much>, <Choice: The sky>]>

>>> 

 

timezone.now()

>>> timezone.now()

datetime.datetime(2019, 10, 5, 2, 20, 10, 762960, tzinfo=<UTC>)

>>> tz = timezone.now()

tz.year

>>> tz.year

2019

tz.month

>>> tz.month

10

tz.day

>>> tz.day

5

tz.hour

>>> tz.hour

2

tz.minute

>>> tz.minute

20

tz.second

 

>>> tz.second

22

tz.tzinfo

>>> tz.tzinfo

<UTC>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM