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>

猜你喜欢

转载自www.cnblogs.com/xiaxiaoxu/p/11665817.html
今日推荐