一、 数据库配置
默认是sqlite3数据库,数据库文件在项目目录(helloDjango)下: djangoDemo/helloDjango/db.sqlite3
在使用ORM模型之前, 先生成迁移文件 makemigrations, 再执行迁移命令 migrate,生成模型对应的数据库表。
django_migrations: 迁移记录表; 每次生成,执行迁移会在这张表中进行检索; 复用数据库时,需要迁移记录。
注意: 一旦生成了迁移文件并且迁移成功之后, 不要删除迁移文件。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | (venv) E:\PythonLearn\djangoDemo\helloDjango>python manage.py makemigrations Migrations for 'mainapp' : mainapp\migrations\ 0001_initial .py ### 定义了 Migration 类 - Create model UserEntity (venv) E:\PythonLearn\djangoDemo\helloDjango>python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, mainapp, sessions Running migrations: Applying contenttypes. 0001_initial ... OK Applying auth. 0001_initial ... OK Applying admin. 0001_initial ... OK Applying admin. 0002_logentry_remove_auto_add ... OK Applying contenttypes. 0002_remove_content_type_name ... OK Applying auth. 0002_alter_permission_name_max_length ... OK Applying auth. 0003_alter_user_email_max_length ... OK Applying auth. 0004_alter_user_username_opts ... OK Applying auth. 0005_alter_user_last_login_null ... OK Applying auth. 0006_require_contenttypes_0002 ... OK Applying auth. 0007_alter_validators_add_error_messages ... OK Applying auth. 0008_alter_user_username_max_length ... OK Applying auth. 0009_alter_user_last_name_max_length ... OK Applying mainapp. 0001_initial ... OK Applying sessions. 0001_initial ... OK |
二、 Model模型
编写 mainapp/models.py; 定义UserEntity 模型; Meta 绑定数据库的表
1 2 3 4 5 6 7 | class UserEntity(models.Model): # 默认会自动创建id主键 name = models.CharField(max_length = 20 ) age = models.IntegerField(default = 0 ) phone = models.CharField(max_length = 11 ) # 指定当前模型类 映射成 哪一张表 class Meta: db_table = 't_user' |
三、 数据CRUD
CRUD简介
- 查询:objects.XXX() ModelEntity.objects.get(pk=id)
- 删除:delete() obj.delete() 基于查询, 先查询出来, 再执行删除
- 更新:save() obj.save() 基于查询, 先查询出来, 再去修改,存储
- 新增:save() obj.save()
- 插入:create() ModelEntity.objects.create(no=uuid.uuid4(), name='Tom',status=True)
- car = {"name": "大众", price: 23.9} Car.objects.create(**car)
3.1 CRUD之查询 all()
1 2 3 4 | def user_list3(request: HttpRequest): users = UserEntity.objects. all () msg = '最佳创业团队' return render(request, 'user/list2.html' , locals ()) |
3.2 CRUD之新增 save()
1 2 3 4 5 6 7 | def add_user(request: HttpRequest): user = UserEntity() user.name = '唐僧' user.age = 24 user.phone = '15700001111' user.save() return redirect( '/user/list' ) |
获取传入变量,新增数据
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | def add_user(request: HttpRequest): # 从请求中获取数据; request.GET是 dict字典类型,保存了GET参数 name = request.GET.get( 'name' , None ) age = request.GET.get( 'age' , 0 ) phone = request.GET.get( 'phone' , None ) if not all ((name, age, phone)): return HttpResponse( '<h3 style="color:red">请求参数不完整</h3>' , status = 400 ) user = UserEntity() user.name = name user.age = age user.phone = phone user.save() return redirect( '/user/list' ) |
1 2 3 4 5 6 7 8 | # 错误请求日志 [ 01 / Apr / 2023 21 : 43 : 26 ] "GET /user/add?name=%E5%AD%99%E6%82%9F%E7%A9%BA HTTP/1.1" 400 48 [ 01 / Apr / 2023 21 : 44 : 29 ] "GET /user/add?name=%E5%AD%99%E6%82%9F%E7%A9%BA&age=500 HTTP/1.1" 400 48 正常请求: http: / / 127.0 . 0.1 : 8000 / user / add?name = 孙悟空&age = 500 &phone = 15700002222 # 正常请求日志 [ 01 / Apr / 2023 21 : 48 : 20 ] "GET /user/add?name=%E5%AD%99%E6%82%9F%E7%A9%BA&age=500&phone=15700002222 HTTP/1.1" 302 0 [ 01 / Apr / 2023 21 : 48 : 20 ] "GET /user/list HTTP/1.1" 200 379 |
3.3 CRUD之更新
更新请求, 先判断是否有id参数, 根据id 查询判断用户是否存在, 用户存在且传递了更新参数则进行更新
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | def update_user(request: HttpRequest): # 请求参数包括 id, name, phone # 通过模型查询 id的用户是否存在; Model类.objects.get(); 不存在则捕获异常 q_id = request.GET.get( "id" , None ) if not q_id: return HttpResponse( 'id参数必须提供' , status = 400 ) try : user = UserEntity.objects.get(pk = int (q_id)) name = request.GET.get( 'name' , None ) phone = request.GET.get( 'phone' , None ) # any: name 或 phone 参数 任意一个存在即为True if any ((name, phone)): if name: user.name = name if phone: user.phone = phone user.save() return redirect( '/user/list' ) else : return HttpResponse( '请提供用户 %s 要更新的信息,如 name 或 phone.' % q_id, status = 400 ) except : return HttpResponse( 'Id为 %s 的用户不存在' % id , status = 400 ) |
3.4 CRUD之删除
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | def delete_user(request: HttpRequest): q_id = request.GET.get( "id" ) if q_id: try : user = UserEntity.objects.get(pk = int (q_id)) user.delete() html = """ <p> Id为 %s的用户删除成功! 三秒后自动跳转到列表 <a href="/user/list"> </p> <script> </script> """ % q_id return HttpResponse(html) except : return HttpResponse( 'Id为 %s 的用户不存在' % q_id) else : return HttpResponse( '必须提供id参数' ) |
3.5 添加路由
1 2 3 4 5 6 7 8 | urlpatterns = [ path( 'user' , user_list), path( 'user2' , user_list2), path( 'list' , user_list3), path( 'add' , add_user), path( 'update' , update_user), path( 'delete' , delete_user), ] |
3.6 CRUD之路由重定向问题: redirect 的路径必须以"/" 开头
1 2 3 4 | # 重定向的路径没有以"/" 开头报错, 定向路径多加一层 return redirect( 'user/list' ) [ 01 / Apr / 2023 21 : 45 : 21 ] "GET /user/user/list HTTP/1.1" 404 2716 |
分类:
23Django/Flask
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?