以上运算符都区分大小写,在这些运算符前加上i表示不区分大小写,
如iexact、icontains、istartswith、iendswith.insert into tb_bookinfo()values()新增--savebook = BooksInfo(bookname = '红楼梦',bookpubtime = date(1930,9,1),bookauthor = '曹雪芹')character = CharacterInfo(
charactername = '猪八戒',charactergender = 1,characterage = 55,chac_description = '猪悟能',cbook = book)新增--create
CharacterInfo.objects.create(charactername = '女儿国国王',charactergender = 1,characterage = 20,chac_description = '女儿美',cbook = book)查询多条记录--返回的是列表
BooksInfo.objects.all()CharacterInfo.objects.all()查询记录条数
BooksInfo.objects.count()CharacterInfo.objects.count()查询单条记录
book = BooksInfo.objects.get(bookname = '西游记')BooksInfo.objects.get(id=1)BooksInfo.objects.filter(id__exact=1)模糊查询
BooksInfo.objects.filter(bookname__contains='梦')BooksInfo.objects.filter(bookname__endswith='义')BooksInfo.objects.filter(bookname__startswith='西')BooksInfo.objects.filter(bookname__istartswith='西')空查询
BooksInfo.objects.filter(bookname__isnull = False)范围查询
BooksInfo.objects.filter(id__in=[1,2,4])属性与常量之间的比较查询:大于,大于等于,小于,小于等于,exclude
BooksInfo.objects.filter(id__gt=3)BooksInfo.objects.filter(id__gte=2)BooksInfo.objects.filter(id__lt=3)BooksInfo.objects.filter(id__lte=3)BooksInfo.objects.exclude(id=1)日期查询
year、month、day、week_day、hour、minute、second:对日期时间类型的属性进行运算BooksInfo.objects.filter(bookpubtime__year=1930)BooksInfo.objects.filter(bookpubtime__gt=date(1930,9,1))属性与属性的比较:F(属性名)
from django.db.models import FBooksInfo.objects.filter(bookcommentcount__gte=F('bookreadcount'))BooksInfo.objects.filter(bookcommentcount__gte=F('bookreadcount')*2)and 查询
BooksInfo.objects.filter(bookauthor__contanins='罗',bookname__startswith='三')or查询Q(属性名__运算符=值)使用&、|连接,&表示逻辑与,|表示逻辑或,~操作符表示非not
BooksInfo.objects.filter(Q(bookreadcount__gt=300)|Q(bookname__contains='吴'))BooksInfo.objects.filter(~Q(pk=3))BooksInfo.objects.filter(~Q(id=3))聚合查询--返回的是字典
BooksInfo.objects.aggregate(Sum('bookreadcount'))使用count时一般不使用aggregate()过滤器BooksInfo.objects.count()排序
BooksInfo.objects.all().order_by('bookreadcount')BooksInfo.objects.all().order_by('-bookreadcount')关联查询语法:一到多,多的模型类名小写
一对应的模型类对象.多对应的模型类名小写_setb = BooksInfo.objects.get(id=1)b.characterinfo_set.all()多到一
c = CharacterInfo.objects.get(id=1)c.cbook访问一模型的id:多对应的模型类对象.关联类属性_idc.cbook_id关联过滤查询:多的模型类名小写
BooksInfo.objects.filter(characterinfo__charactername='贾宝玉')BooksInfo.objects.filter(characterinfo__charactername__contains='玉')BooksInfo.objects.filter(characterinfo__characterage__gt=30)修改:单条修改
c = CharacterInfo.objects.get(charactername='猪八戒')c.charactername='猪哥哥'c.save()批量修改CharacterInfo.objects.filter(charactername='林黛玉').update(charactername='林妹妹')删除:
模型类对象deletec = CharacterInfo.objects.get(id=3)c.delete()模型类.objects.filter().delete()CharacterInfo.objects.filter.(id=14).delete()Django查询结果集
BooksInfo.objects.all()BooksInfo.objects.filter(bookreadcount__gt=30).order_by('bookpubtime')b = BooksInfo.objects.exclude(bookname__contains='三')确定查询集中是否有数据b.exists()