Python学习18

python(认识API,django的数据库操作增、删、改、查)

1、认识API

API会帮助进入交互式 Python 命令行

  • manage.py 会设置 django_settings_module 环境变量,这个变量会让 Django 根据
    mysite/settings.py 文件来设置 Python 包的导入路径

python manage.py shell #进入命令行界面


1、数据库的相关操作

1、通过 python manage.py shell,在次进入Python 交互式命令行:

from polls.models import Choice, Question :引入polls应用并且引入Choice,Question类即两个数据表

2、在django中向数据库插入数据:

方法一

  • q = Question(question_text=“What’s new?”,pub_date=timezone.now()) #向Question插入内容

方法二

  • c = Question()
    c.question_text= ‘yyt’
    c.pub_date = timezone.now() c.save()

方法三

  • d= Question.objects.create(question_text = ‘1234’,pub_date = ‘4567’) : 这种方法可以不用save()

方法四

  • f1 = Question(question_text = ‘789’,pub_date =timezone.now()):批量多条数据一起添加
    f2 = Question(question_text = ‘123’,pub_date =timezone.now()) > obj_list = [f1,f2]
    t=Question.objects.bulk_create(obj_list)
>>>from polls.models import Choice, Question #引入Choice和Question
>>>Question.objects.all() #查询Question的相关全部内容
>>>a = Question.objects.all()
>>>a[0].question_text #可以取出question_text的内容
>>>a[0].pub_date #可以取出pub_date的相关内容
>>>from django.utils import timezone #引入timezone模块
#插入数据的第一种方式:
>>>q = Question(question_text="What's new?", pub_date=timezone.now()) #向Question插入内容
>>>q.save() #保存修改
>>>q.id #获取当前插入数据的id,方便一对多的数据插入
>>>q.question_text #打印显示question_text的内容
>>>q.pub_date #打印显示pub_date的内容
>>>q.question_text = "What's up?" #修改question_text的内容,重新赋值
>>>q.save()
#插入数据的第二种方法:
>>>c = Question()
>>>c.question_text = 'yyt'
>>>c.pub_date = timezone.now()
>>>c.save()
#插入数据的第三种方法:
>>>d= Question.objects.create(question_text = '1234',pub_date = timezone.now())
>>> d.question_text

 

 

3、为了让Question.objects.all()能返回一些内容,polls/models.py 中编码如下:

Question 和 Choice 增加 str() 方法

from django.db import models
class Question(models.Model):
    # ...
    def __str__(self):
        return self.question_text
class Choice(models.Model):
    # ...
    def __str__(self):
        return self.choice_text

 

 

Question.objects.all() 会发现与刚才修改之前的输出不一样

>>>Question.objects.all()
<QuerySet [<Question: hello world!>, <Question: wh
at`s new?>, <Question: yyt>]>

 

 

4、新建一个方法:was_published_recently

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

 

在django中可以用某个数据调用上个方法:

>>>b = Question.objects.get(pk = 2)
>>> b
>>> b.was_published_recentli()

 

 

5、在django中向数据库查询数据:

方法一

  • Question.objects.filter(id=1) 指定id=1的一条数据查询

方法二

  • d = dict(question_text = ‘789’,pub_date = timezone.now())
    e= Question.objects.get_or_create(**d)

方法三
v = Question.objects.all()[:3]:查询前三条数据

方法四
v = Vocation.object.values(‘job’):查询单个字段 数据以元组加列表的形式返回

方法五
v = Vocation.objects.values():数据以字典的形式返回

方法六
t = Question.objects.get(id=1):使用get方法查询
t.question_text

方法七
v =Question.objects.filter(id=3):使用filter也可以按照条件查询,但是查询多条的
v[0].question

方法八
v = Question.objects.filter(id=3,question_text = ‘xxxxx’) :filter多条件查询
或者
d =dict(id=1,question_text = ‘xxxxx’)
v = Question.objects.filter(**d)

__exact 精确等于 like ‘aaa’
__iexact 精确等于 忽略大小写 ilike ‘aaa’
__contains 包含 like ‘%aaa%’
__icontains 包含 忽略大小写 ilike ‘%aaa%’,但是对于sqlite来说,contains的作用效果等同于icontains。
__gt 大于
__gte 大于等于
__lt 小于
__lte 小于等于
__in 存在于一个list范围内
__startswith 以…开头
__istartswith 以…开头 忽略大小写
__endswith 以…结尾
__iendswith 以…结尾,忽略大小写
__range 在…范围内
__year 日期字段的年份
__month 日期字段的月份
__day 日期字段的日
__isnull=True/False
__isnull=True 与 __exact=None的区别

 

 

6、在django中向数据库更新数据:

方法一

  • a = Question.objects.get(id = 1)
    a.question_text = ‘xxxxx’
    a.save()

方法二

  • t = Question.objects.filter(id=1).update(question_text = ‘xxxxx’)
    也可以写成
    d = dict(question_text = ‘xxxxx’)
    t = Question.objects.filter(id=1).update(**d)

方法三

  • from django.db.models import F
    from django.db.models import *
    t= Types.objects.filter(id=1)
    t.update(id=F(‘id’)+10) :让id = 1的都加10

7、在django中删除数据库数据:

方法一
删除全部数据 Question.objects.all().delete()
删除一条数据 Question.objects.get(id=1).delete()
删除多条数据 Question.objects.filter(question_text = ‘xxxxx’).delete()

Question.objects.filter(id=1) #查找id=1的数据
Question.objects.filter(question_text__startswith='What') #查找以what结尾的数据
from django.utils import timezone
current_year = timezone.now().year #现在的年份
Question.objects.get(pub_date__year=current_year)
a = Question.objects.get(id=2) #获取id=2的数据
a.question_text = 'hahahah' #将获取到id=2的数据修改为‘hahahah’
a.save()
Question.objects.get(pk=1)
q = Question.objects.get(pk=1)
q.was_published_recently() #调用了was_published_recently函数
q = Question.objects.get(pk=1)
q.choice_set.all()
q.choice_set.create(choice_text='Not much', votes=0)
q.choice_set.create(choice_text='The sky', votes=0)
c = q.choice_set.create(choice_text='Just hacking again', votes=0)
c.question
q.choice_set.all()
q.choice_set.count()
Choice.objects.filter(question__pub_date__year=current_year)
c.delete()
posted @ 2020-12-31 14:58  MFTang  阅读(395)  评论(0编辑  收藏  举报