django连接mongodb数据库

一、环境基本步骤

  • 1、进入开发环境的虚拟空间,不知道的请看传送门

  • 2、基本包的版本

  • 3、安装包

  • pip install mongoengine
  • 4、创建一个新的django项目,并指定到虚拟空间的python.exe

  • 二、在django中配置

  • 1、在settings.py中进行基本的配置

  • DATABASES = {
        'default': {
            'ENGINE': None, # 把默认的数据库连接至为None
        }
    }
    from mongoengine import connect
    connect('test') # 连接的数据库名称
  • 2、新建一个app

  • 3、在新建的appmodels.py中新建数据模型

import mongoengine

class StudentModel(mongoengine.Document):
    name = mongoengine.StringField(max_length=16)
    age = mongoengine.IntField(default=0)

        4.在视图文件中创建一个视图

from django.shortcuts import render, HttpResponse

# Create your views here.
# .表示当前包下的models
from .models import StudentModel
from django.views.generic import View

class Student(View):
    def get(self, request):
        StudentModel.objects.create(name='水痕', age= 20)
        return HttpResponse('hello word')
        

5、配置url

from django.conf.urls import url
from django.contrib import admin
from student.views import Student
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^student/$', Student.as_view(),name='student')
]

三、关于增删改查

  • 1、增加数据

  • 2、查询数据(返回的是一个QuerySet)

class Student(View):
def get(self, request):
    result = StudentModel.objects.filter(name='水痕')
    print(result[0].age)
    return HttpResponse('hello word')

     3、修改数据

class Student(View):
def get(self, request):
    result = StudentModel.objects.filter(name='水痕').first().update(name='张三')
    print(result)
    return HttpResponse('hello word')

4、删除数据

class Student(View):
def get(self, request):
    result = StudentModel.objects.filter(name='张三').first().delete()
    print(result)
    return HttpResponse('hello word')

四、关于更多参考文档

猜你喜欢

转载自blog.csdn.net/weixin_42670402/article/details/87979567
今日推荐