Django操作mongo数据库一(配置文件里写连接信息)
一、基本环境
1、开发环境:
Python环境:Python 3.8.16
Django环境:4.1
2、需要安装的包
pip install pymongo
pip install mongoengine
二、开发参数配置
1、先创建一个mongoApp的应用
2、增加mongo库的连接
3、创建数据模型
4、引入mongoApp的urls
5、编写对mongo哭的增删改查方法(核心)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | from .models import UserInfo from django.http import HttpResponse #新增一个对象 def add( self ): userInfo = UserInfo.objects.create( code = '1' , name = 'zhangsan' , age = '18' , count = 1 , ) print (userInfo) return HttpResponse( "add success" ) #查询一条数据(使用get查询多条数据会报错) def getSingle( self ): userInfo = UserInfo.objects.get(code = "1" ) print (userInfo) return HttpResponse( "getSingle success" ) #查询所有数据 def getAll( self ): userInfoList = UserInfo.objects. all () for i in range ( len (userInfoList)): print (i, '---->' , userInfoList[i]) return HttpResponse( "getAll success" ) #查询多条数据,增加查询条件 def getAllSelect( self ): userInfoList = UserInfo.objects. filter (code = "1" ,name = "lisi" ) for i in range ( len (userInfoList)): print (i, '---->' , userInfoList[i]) return HttpResponse( "getAll success" ) #删除数据(删除所有) def delete( self ): UserInfo.objects.delete() return HttpResponse( "delete success" ) # 更新 def update( self ): userInfo = UserInfo.objects. filter (code = "1" ) userInfo.update(age = "22" ,count = 2 ) return HttpResponse( "update success" ) #删除单条(查询出来就是单条,这里使用get把所有的数据都删除了) def deleteSingle( self ): userInfo = UserInfo.objects. filter (code = "4" ) userInfo.delete() return HttpResponse( "deleteSingle success" ) |
6、配置方法的访问路径
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!