接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]
本文详细介绍了Django ORM的查询与数据修改操作,包括使用get、all、filter方法筛选数据,利用in、gt/gte等条件过滤,以及对日期字段的操作。此外,还展示了如何批量修改、删除数据,以及数据返回后的展示方式,如values和order_by等。掌握这些技巧能帮助开发者更高效地管理数据库。
3173

被折叠的 条评论
为什么被折叠?



