在项目中的models.py新建一个类
class Student(models.Model): s_name = models.CharField(max_length=10) s_age = models.IntegerField(default=1)
在terminal终端中运行, python manage.py makemigrations, 创建迁移文件夹
python manage.py migrate
数据库中就有了student数据表
在urls.py中 加一个 re_path
然后在views.py中加入add_student函数
def add_student(request): student = Student() student.s_name = 'mei%d' % random.randrange(100) # age字段因为设置了默认值1 ,所以不用添加 student.save() # 此处一定要带上() return HttpResponse("添加到数据库成功%s" % student.s_name)
注意 继承类 有括号 **** save也要有括号
获取记录get
def get_students(request): students = Student.objects.all() #for student in students: # print(student.s_name) context = { "gap1": "这是填第一个位置", "gap2": "这是第二个", "students":students, } return render(request, 'studentlist.html', context=context)
<html lang="en"> <head> <meta charset="UTF-8"> <title>学生列表</title> </head> <body> <h1>{{ gap1 }}</h1> <h2>{{ gap2 }}</h2> <h1>学生列表如下:</h1> <ul> {% for student in students %} <li>{{ student.s_name }}</li> <li>{{ student.s_age }}</li> {% endfor %} </ul> </body> </html>
def update_student(request): student=Student.objects.get(pk=5) #此处的pk是premary key的主键意思 student.s_name='改名了' student.save() return HttpResponse("修改学生姓名成功!改成了%s" % student.s_name)
def delete_student(request): student=Student.objects.get(pk=4) student.delete() return HttpResponse("%s删除成功" % student.s_name)