django-数据库的增删改查操作
models.py中执行如下操作
class UserInfo(models.Model):
userid = models.AutoField(primary_key=True)
username = models.CharField(max_length=30, null=False)
password = models.CharField(max_length=128, null=False)
regtime = models.DateTimeField(auto_now=True)
class Meta:
db_table = 'userinfo'
# ordering 排序,默认按照主键排序
def __str__(self):
return self.username
在项目urls.py中执行如下操作
urlpatterns = [
path('admin/', admin.site.urls),
path('login/', include('loginapp.urls'))
]
在app的urls.py中执行如下操作
urlpatterns = [
# path('login/', views.login)
# path('query/', views.query)
# path('curd/', views.curd)
# path('order/', views.order)
# path('dis/', views.distinctview)
# path('fx/', views.fx)
# path('query/', views.process_query, name='curd')
path('group/', views.group)
]
views.py试图文件中执行如下操作
1.添加用户记录
def login(request):
增加用户记录 使用save()方法来增加记录
username = UserInfo(username='tom', password='123')
username.save()
2.使用遍历方法创建用户信息
user = {'username': 'wangwang', 'password': '1234'}
UserInfo.objects.create(**user)
3.增加用户方法2
UserInfo.objects.create(username='wangwei', password='111')
批量插入 嵌套create方法在shell中执行
UserInfo.objects.create(UserInfo.objects.create(username='wangjian', password='222'),
UserInfo.objects.create(username='wanghui', password='222'),
UserInfo.objects.create(username='wanglong', password='222'))
4.批量插入方法2
UserInfo.objects.bulk_create([UserInfo(username='huihui', password='222'),
UserInfo(username='dongmao', password='222'),
UserInfo(username='zhouzhou', password='222'),
UserInfo(username='dongmao1', password='222'),
UserInfo(username='zhouzhou1', password='222')
])
6. 修改用户记录 先查看是否有该字段,然后调用字段直接进行修改
user = UserInfo.objects.get(userid=1)
print(user)
user.password = '3333'
user.save()
7. 删除用户记录 使用delete方法删除指定行
user = UserInfo.objects.get(userid=2)
print(user, type(user))
if user:
user.delete()
8.批量删除多条记录
users = UserInfo.objects.filter(userid__gte=2)
print(users)
users.delete()
9.数据查询
firstname = ["张", "李", "郑", "吴", "赵", "周", "王"]
lastname = ["建军", "建辉", "建业", "建党", "建国"]
users = []
for name in range(100):
username = firstname[randint(0, 6)] + lastname[randint(0, 4)]+str(randint(0, 10000))
users.append(UserInfo(username=username, password=str(randint(11111, 999999))))
UserInfo.objects.bulk_create(users)
return HttpResponse("批量查询")
10.使用过滤器查询数据
def query(request):
# all过滤器查询所有数据
users = UserInfo.objects.all()
print(users)
return render(request, 'index.html', locals())
# filter 过滤器 条件查询
users = UserInfo.objects.filter(userid__gt=100).filter(userid__lt=200)
print(users)
return render(request, 'index.html', locals())
11.def curd(request):
# 数据查询
user = UserInfo()
user.username = '王辉'
user.password = '2222222'
user.save()
return HttpResponse("CURD")
12.数据排序 使用order_by()方法进行排序
[:number]切片取第前number条记录
def order(request):
data = UserInfo.objects.order_by('username')
for user in data:
print(user.username)
return HttpResponse("排序")
13.查询指定字段
def curd(request):
data = UserInfo.objects.all().values('username')
for user in data:
print(user)
14.去除查询中重复字段
def distinctview(request):
data = UserInfo.objects.all().values("password").distinct()[:10]
print(data)
15.反序 使用reverse方法
def fx(request):
data = UserInfo.objects.order_by('userid').reverse()
print(data)
return HttpResponse("curd")
16.非过滤器查询方法
def process_query(request):
get方法只能返回一条记录
user = UserInfo.objects.get(userid=100)
print("111")
print(user)
17.使用first方法返回一个对象
user = UserInfo.objects.first()
print(user)
18.返回最后一个对象 使用last()方法
user = UserInfo.objects.last()
print(user)
19.查询结果集中的记录数目
num = UserInfo.objects.filter(userid__gte=17).count()
print(num)
20.判断结果集是否为空
flag = UserInfo.objects.filter(userid__lt=17).all().exists()
print(flag)
return HttpResponse("非过滤器查询方法")
"""
关系运算符的表达式的使用
>= 字段__get=num
> 字段__gt=num
< 字段__lt=num
<= 字段__lte=num
== 字段=num
!= 字段__ne=num
"""
21.多个条件查询的逻辑与连接,查询出大于等于100小于200的用户
user = UserInfo.objects.filter(userid__lt=200, userid__gte=100)
print(user)
22.集合查询
data = UserInfo.objects.filter(userid__in=[17, 18, 19])
print(data)
23.查询字段是否为空
data = UserInfo.objects.filter(username__isnull=True)
print(data)
24.字符串操作查询
# __startwith以什么字符串开头的所有字段
data = UserInfo.objects.filter(username__startswith='张')
for user in data:
print(user)
25.使用正则表达式匹配查询 使用————reges方法
data = UserInfo.objects.filter(username__regex=r'3$')
print(data)
26.日期查询操作
data = UserInfo.objects.filter(regtime__year=2021)
print(data)
return HttpResponse("多条件的逻辑与查询")
27.统计查询
def group(request):
#查询最大userid
userid = UserInfo.objects.aggregate(Max('userid'))
print(userid)
# 查询最小值userid
userid = UserInfo.objects.aggregate(Min('userid'))
print(userid)
# 统计分组查询
data = UserInfo.objects.values('username').annotate(Count('userid')).filter(userid=30)
print(data)
return HttpResponse("统计查询")