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

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

如今咱們進入交互式python命令行,嘗試一下django爲你建立的各類API,經過如下命令打開python命令行:python

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

 

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

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.django

(InteractiveConsole)工具

 

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

 

當咱們成功進入命令行後,來試試database API:命令行

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

#導入模型類code

>>> from polls.models import Choice, Questionorm

#查詢模型類數據對象

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

相關文章
相關標籤/搜索