Django笔记
from app01 import models
models.Book.objects.create(name="python",price=88,pub_date='2017-05014')
pymysql.err.IntegrityError: (1048, "Column 'publisher_id' cannot be null")
models.Publisher.objects.create(name="TsingHua Publisher",website="http://www.tsinghuaedu.com")
<Publisher: Publisher object>
models.Publisher.objects.create(name="Youdian Publisher",website="http://www.youdianedu.com")
>>> models.Book.objects.create(name="python",price=88,pub_date='2017-05-14',publisher_id=1)
<Book: Book object>
>>> models.Book.objects.create(name="linux",price=22,pub_date='2016-03-14',publisher_id=1)
<Book: Book object>
>>> models.Book.objects.create(name="Go",price=50,pub_date='2018-09-14',publisher_id=2)
<Book: Book object>
#查看所有的书籍
>>> models.Book.objects.all()
<QuerySet [<Book: Book object>, <Book: Book object>, <Book: Book object>]>
在modules下增加以下配置
def __str__(self):
return self.name
退出重新登录
D:\python\oldboy\day16\170514\MyDjangoProject>python manage.py shell
Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:18:55) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from app01 import models
>>> models.Book.objects.all()
<QuerySet [<Book: python>, <Book: linux>, <Book: Go>]>
字符串拼接:
def __str__(self):
return "%s %s"%(self.name,self.website)
>>> models.Book.objects.all()[0]
<Book: python>
>>> b1=models.Book.objects.all()[0]
>>> b1.authors
<django.db.models.fields.related_descriptors.create_forward_many_to_many_manager.<locals>.ManyRelatedManager object at 0x000000000438F748>
>>> b1.authors.all() #查看作者
<QuerySet []>
>>> models.Author.objects.create(name='alex',email='alex@126.com')
<Author: Author object>
>>> models.Author.objects.create(name='jack',email='jack@126.com')
<Author: Author object>
>>> models.Author.objects.create(name='OldBoy',email='ob@126.com')
<Author: Author object>
创建作者
>>> b4=models.Book.objects.create(name="Jinpingmei",price=199,publisher_id=2,pub_date="2016-07-21")
>>> b4
<Book: Jinpingmei>
>>> b4.authors.add(1,2)
>>> b4.save()
删除作者
>>> b4.authors.remove(1)
>>> b4.save()
>>> b4.authors.all()
<QuerySet [<Author: jack>]>
查询
objects.filter 返回列表
objects.all 返回all
models.Book.objects.last() first()
>> p1.book_set.all() 多个图书关联了同一个出版社,通过出版社反向查出版了多少图书
objects.get 返回单个对象或错误
app01.models.DoesNotExist: Book matching query does not exist.
app01.models.MultipleObjectsReturned: get() returned more than one Book -- it re
objects.get_or_create() 如果没有就创建
>>> models.Book.objects.get_or_create(name="Java", publisher_id=2, pub_date="2019-01-02")
(<Book: Java>, True)
ORM之查(filter,value)
包含
>>> models.Book.objects.filter(name__contains="Go")
<QuerySet [<Book: Go>]>
---------------了不起的双下划线(__)之单表条件查询----------------
# models.Tb1.objects.filter(id__lt=10, id__gt=1) # 获取id大于1 且 小于10的值
#
# models.Tb1.objects.filter(id__in=[11, 22, 33]) # 获取id等于11、22、33的数据
# models.Tb1.objects.exclude(id__in=[11, 22, 33]) # not in
#
# models.Tb1.objects.filter(name__contains="ven")
# models.Tb1.objects.filter(name__icontains="ven") # icontains大小写不敏感
#
# models.Tb1.objects.filter(id__range=[1, 2]) # 范围bettwen and
#
# startswith,istartswith, endswith, iendswith,
查询相关API:
# <1>filter(**kwargs): 它包含了与所给筛选条件相匹配的对象
# <2>all(): 查询所有结果
# <3>get(**kwargs): 返回与所给筛选条件相匹配的对象,返回结果有且只有一个,如果符合筛选条件的对象超过一个或者没有都会抛出错误。
#-----------下面的方法都是对查询的结果再进行处理:比如 objects.filter.values()--------
# <4>values(*field): 返回一个ValueQuerySet——一个特殊的QuerySet,运行后得到的并不是一系列 model的实例化对象,而是一个可迭代的字典序列
# <5>exclude(**kwargs): 它包含了与所给筛选条件不匹配的对象
# <6>order_by(*field): 对查询结果排序
# <7>reverse(): 对查询结果反向排序
# <8>distinct(): 从返回结果中剔除重复纪录
# <9>values_list(*field): 它与values()非常相似,它返回的是一个元组序列,values返回的是一个字典序列
# <10>count(): 返回数据库中匹配查询(QuerySet)的对象数量。
# <11>first(): 返回第一条记录
# <12>last(): 返回最后一条记录
# <13>exists(): 如果QuerySet包含数据,就返回True,否则返回False
>>> models.Book.objects.filter(pub_date__range=('2015-01-01','2017-01-01'))
<QuerySet [<Book: linux>, <Book: Jinpingmei>]>
官方文档:
https://docs.djangoproject.com/en/1.11/ref/models/querysets/
__contains
__icontains 忽略大小写
__startswith
__endswith
__endswith
models.Book.objects.filter(pub_date__range=('2015-01-01','2017-01-01'))
Entry.objects.filter(pub_date__date=datetime.date(2005, 1, 1))
Entry.objects.filter(pub_date__year=2005)
Entry.objects.filter(pub_date__year__gte=2005)
Entry.objects.filter(pub_date__day=3)
Entry.objects.filter(pub_date__day__gte=3)
Entry.objects.filter(pub_date__week_day=2)
Entry.objects.filter(pub_date__week_day__gte=2)
Entry.objects.filter(pub_date__isnull=True)
>>> models.Book.objects.exclude(price=None) 反查询
<QuerySet [<Book: py>, <Book: linux>, <Book: Go>, <Book: Jinpingmei>]>
models.Book.objects.values('name','price')
aggregate 聚合
参考链接:https://docs.djangoproject.com/en/1.11/topics/db/aggregation/
from django.db.models import Avg,Max,Min,Sum,Count
>>> models.Book.objects.all().aggregate(Avg('price'))
>>> models.Book.objects.values('publisher__name').annotate(Avg('price')) 统计所有书籍的平均价格
<QuerySet [{'publisher__name': 'TsingHua Publisher', 'price__avg': 22.0}, {'publ
isher__name': 'Youdian Publisher', 'price__avg': 124.5}]>
>>> models.Book.objects.all().aggregate(Avg('price'))
{'price__avg': 89.75}
>>> models.Book.objects.values('name','price').count()
6
>>> models.Book.objects.create(name="py3 dev",publisher_id=1,pub_date='2018-09-10')
<Book: py3 dev>
正则匹配
>>> models.Book.objects.filter(name__regex=r"^G")
<QuerySet [<Book: Go>]>
>>> models.Book.objects.filter(name__regex=r"o$")
<QuerySet [<Book: Go>]>
Entry.objects.get(title__regex=r'^(An?|The) +')
>>> from django.db.models import Avg,Sum,Count
>>> models.Book.objects.values('publisher__name').annotate(Count('id'))
<QuerySet [{'publisher__name': 'TsingHua Publisher', 'id__count': 3}, {'publishe
r__name': 'Youdian Publisher', 'id__count': 3}]>
>>> models.Book.objects.values('publisher__name').annotate(Avg('price'))
<QuerySet [{'price__avg': 55.0, 'publisher__name': 'TsingHua Publisher'}, {'pric
e__avg': 124.5, 'publisher__name': 'Youdian Publisher'}]>
F:将所有书籍价格取出来分别+10
>>> from django.db.models import F
>>> models.Book.objects.values('price')
<QuerySet [{'price': 88}, {'price': 22}, {'price': 50}, {'price': 199}, {'price'
: None}, {'price': None}]>
>>> models.Book.objects.update(price=F('price')+10)
6
>>> models.Book.objects.values('price')
<QuerySet [{'price': 98}, {'price': 32}, {'price': 60}, {'price': 209}, {'price'
: None}, {'price': None}]>
http://www.cnblogs.com/alex3714/articles/5512568.html
F
自修改
Entry.objects.all().update(n_pingbacks=F('n_pingbacks') + 1)
本表内两个字段比较
>>> from django.db.models import F
>>> Entry.objects.filter(n_comments__gt=F('n_pingbacks'))
字段数据迁移
# THIS WILL RAISE A FieldError
>>> Entry.objects.update(headline=F('blog__name'))
Q