学习目标:
Python学习十六-Django、
学习内容:
1、认识API
2、django数据库的相关操作
3、其他django数据库操作
1、认识API
API会帮助进入交互式 Python 命令行
- manage.py 会设置 django_settings_module 环境变量,这个变量会让 Django 根据
mysite/settings.py 文件来设置 Python 包的导入路径
python manage.py shell #进入命令行界面
2、django数据库的相关操作
- 后续会用到的django的models
models.py
import datetime
from django.db import models
from django.utils import timezone
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_recentli(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
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
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)
方法九
- 一对多的查询:
逆差询:当一个class中存在一个外键,用这个外键去查询这个表连接的另一个表
b = Question.objects.get(id = 4)
b.choice_set.all() :逆差询中_set表明方向,不用外键
<QuerySet[<Choice: 是>, <Choice: 否>]>
__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()
3、其他django数据库操作
1、查询等于、不等于(‘~’)的关系
v = Question.objects.filter(id__gt=2,question_text=‘what`s new?’)
2、查询或这种关系的条件可以使用Q,不过Q需要引用
from django.db.model import Q v =
Question.objects.filter(Q(id=1)|Q(question_text=‘wy’))
- sql中的不等于查询条件的写法:
v =question.objects.filter(~Q(question_text=‘wy’))
或者
v =Question.objects.exclude(question_text=‘what`s new?’)
3、统计一共多少条数据
v = Question.objects.count()
4、根据id倒序排序同时根据question_text排序
v = Question.objects.order_by(’-id’,‘question_text’)
5、对某一个字段进行去重操作,下面这个还加个条件
v = Question.objects.values(‘question_text’).filter(question_text=‘wy’).distinct()
6、