django基础5--CRUD操作

一.CRUD操作
crud指增删改查
1.增加
from app01 import models
# 获取数据
def add_person(request):
if request.method == ‘POST’:
name = request.POST.get(‘name’)
age = request.POST.get(‘age’)
height = request.POST.get(‘height’)
weight = request.POST.get(‘weight’)
birthday = request.POST.get(‘birthday’)
# 导入数据
person = models.Person()
person.name = name
person.age = age
person.height = height
person.weight = weight
person.birthday = birthday
person.save()
# 方法二:使用create方法
person = models.Person.objects.create(
name = name
age = age
height = height
weight = weight
birthday = birthday

			)
			return redirect('/app01/show_person/')
		return render(request,'app01/add_person.html')

2.展示
	def show_person(request):
		person_obj_lst = models.Person.objects.all()
		return render(request,'app01/show_person.html',{'person_obj_lst':person_obj_lst})
		
3.删除
	def del_person(request):
		ids = request.GET.get('id')
		models.Person.objects.get(id = ids).delete()
		return redirect('/app01/show_person/')

4.修改
	def update_person(request):
		if request.method == 'GET':
			ids = request.GET.get('id') # 此id为show_person页面的id
			person_obj = models.Person.object.get(id = ids)
			return render(request , 'app01/update_person.html',{'person_obj':person_obj})
		else:
			ids = request.POST.get('id') # 获取update_person页面隐藏域里的id
			name = request.POST.get('username')
			age = request.POST.get('age')
			height = request.POST.get('height')
			weight = request.POST.get('weight')
			birthday = request.POST.get('birthday')
			# 导入数据库
			person = models.Person.objects.get(id=ids)
			person.name = name
			person.age = age
			person.height = height
			person.weight = weight
			person.birthday = birthday
			person.save()
			return redirect('/app01/show_person/')

二.admin 使用
1.python manage.py createsuperuser
2.注册 model 类
admin.py :
from django.contrib import admin
from app01.models import Person
admin.site.register(Person)
3. 修改成中文
LANGUAGE_CODE = ‘zh-hans’

三.常用方法
1.all()查询所有结果
2.filter(**kwargs) 包含筛选条件相匹配的对象
3.get(**kwargs) 只返回一个结果
ret = models.Person.objects.get(age=11)
4.first()返回第一条记录
5.last()返回最后一条记录
6.exclude() 返回与筛选条件不匹配的对象
7.order_by()对查询结果排序,默认升序
加’-'降序
8.reverse() 对查询结果反向排序
9.values() 返回一个字典
10.values_list() 返回的是元组
11.count() 计数
12.exists() 如果包含数据返回True 否则返回False

四.切片数据
Person.objects.order_by(‘name’)[0:2]

五.双下划线方法
age__lt 小于
age__lte 小于等于
age__gt 大于
age__gte 大于等于
age__in 包含
name__contains=‘s’ 名字中含有s的
age__range=[10,20] 范围查找
xx__startwith = ‘x’ 以x开头
xx__endwith = ‘x’ 以x结尾
birthday__year = 2019 以时间为筛选条件

你可能感兴趣的:(Django)