Django学习 day7 查询和删改数据

接day6

目录

查询

get 返回一个数据,没有或多个会报错

models.Account.objects.get(id=1)  #get只能查一个数据 

all 返回所有数据

models.Account.objects.all()

filter 条件过滤

models.Account.objects.filter(password='111')  # 获取password为111的所有数据

in

models.Account.objects.filter(id__in=[1,2,4])  # 获取id为1,2,4的数据

gt / gte

models.Account.objects.filter(id__gt=2)  # 获取id大于2的所有数据
models.Account.objects.filter(id__gte=2)  # 获取id大于等于2的所有数据

startswith

models.Account.objects.filter(username__startswith='z')  # 获取username以z开头的所有数据

endswith 获取某参数以什么结尾的所有数据

range
区间过渡,可对数字、日期进行过滤

import datetime
start_date = datetime.date(2005, 1, 1)
end_date = datetime.date(2005, 3, 31)
models.Account.objects.filter(pub_date__range=(start_date, end_date))

data

models.Account.objects.filter(pub_date__date=datetime.date(2005, 1, 1))
models.Account.objects.filter(pub_date__date__gt=datetime.date(2005, 1, 1))

year

models.Account.objects.filter(pub_date__year=2005)
models.Account.objects.filter(pub_date__year__gte=2005)

month 与year同理
day 与year同理
week

models.Account.objects.filter(pub_date__week=52)
models.Account.objects.filter(pub_date__week__gte=32, pub_date__week__lte=38)

week_day
Takes an integer value representing the day of week from 1 (Sunday) to 7 (Saturday)

models.Account.objects.filter(pub_date__week_day=2)
models.Account.objects.filter(pub_date__week_day__gte=2)

regex

models.Account.objects.filter(title__regex=r'^(An?|The) +')

删改

# 批量修改
models.Account.objects.filter(username='elina').update(password="Luffy#21")
 
# 单条修改
obj = models.Account.objects.get(username='linux')
obj.username = 'python'
obj.save()
 
 
# 批量删除
models.User.objects.get(password='oldboy').delete()
 
# 单条删除
obj = models.User.objects.get(id=3)
obj.delete()

数据返回后的展示

values()

>>> Blog.objects.values()
<QuerySet [{'id': 1, 'name': 'Beatles Blog', 'tagline': 'All the latest Beatles news.'}]>
>>> Blog.objects.values('id', 'name')
<QuerySet [{'id': 1, 'name': 'Beatles Blog'}]>

order_by()
排序

Entry.objects.filter(pub_date__year=2005).order_by('-pub_date', 'headline')

reverse()
反向排序

my_queryset.reverse()[:5]
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不会写代码的嘤嘤

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值