添加数据
创建学生模型并添加学生数据
1.前文中已提及模型建立、数据库连接及文件迁移,此处省略
2.学生数据添加方法(写在views中)
def add(requst):
if request.method == 'GET':
return render(request, 'index.html')
if request.method == 'POST':
s_name = request.POST.get('name')
if request.POST.get('sex') == '男':
s_sex = 1
else:
s_sex = 0
#s_sex = request.POST.get('sex')
s_birth = request.POST.get('birth')
s_tel = request.POST.get('tel')
Student.object.create(
s_name = s_name
s_sex = s_sex
s_birth = s_birth
s_tel = s_tel
)
return render(request, 'index.html')
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
2.index.html
<form action="/stu/student/" method="post">
<table>
<tr>
<td>姓名</td>
<td>性别</td>
<td>生日</td>
<td>电话</td>
</tr>
<tr>
<td><input type="text" name="name"></td>
<td><input type="text" name="sex"></td>
<td><input type="date" name="birth"></td>
<td><input type="text" name="tel"></td>
</tr>
</table>
<input type="submit" value="提交">
</form>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
常用数据查询语句
1.查询所有
stus = Student.objects.all()
- 1
2.查询所有女生
stus = Student.objects.filter(stu_sex=False)
- 1
3.get方法
stus = Student.objects.get(stu_sex=True)
- 1
4.查询按照id从大到小排序
stus = Student.objects.all().order_by('-id')
- 1
5.获取id最大的一条数据
stus = Student.objects.all().order_by('-id').first()
- 1
6.获取id最小的一条数据
stus = Student.objects.all().order_by('-id').last()
- 1
- 统计男生数据数量
stus = Student.objects.filter(stu_sex=True).count()
- 1
8.查询所有80后女生信息
stus = Student.objects.filter(stu_sex=False, stu_birth__gte='1980-01-01', stu_birth__lt='1990-01-01')
#注意:gte表示大于等于,lt表示小于
- 1
- 2
9.查询指定姓氏的数据
stus = Student.objects.filter(stu_name__startswith='胡')
- 1
10.查询指定字结尾的数据
stus = Student.objects.filter(stu_name__endswith='乔')
- 1
11.查询姓名中包含指定字的数据
stus = Student.objects.filter(stu_name__contains='美')
- 1
12.判断是否存在某条数据
stus = Student.objects.filter(stu_name='张三').exists()
- 1
13.获取多个id的数据
ids = [1, 2]
stus = Student.objects.filter(id__in=ids)
- 1
- 2
14.查询语文成绩大于数学d学生
stus = Student.objects.filter(stu_yuwen__gte=F('stu_shuxue'))
- 1
15.查询语文高于数学10分以上的学生
stus = Student.objects.filter(stu_yuwen__gte=F('stu_shuxue') + 10)
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Django添加数据、查询数据(转载) - Python技术站