在 Django 项目中连接 MongoDB 数据库,你需要使用一个第三方库,如 djongo
或 mongoengine
pip install djongo
settings.py
文件中,配置数据库设置:DATABASES = {
'default': {
'ENGINE': 'djongo',
'NAME': 'your_database_name',
'CLIENT': {
'host': 'mongodb://localhost:27017/',
}
}
}
pip install mongoengine
settings.py
文件中,配置数据库设置:from mongoengine import connect
connect(
db='your_database_name',
host='mongodb://localhost:27017/'
)
django-admin startproject myproject
cd myproject
django-admin startapp myapp
myapp/models.py
文件中,定义一个简单的模型:from django.db import models
class Person(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
myproject/settings.py
文件中,配置数据库设置(如上所示)。python manage.py makemigrations
python manage.py migrate
myapp/views.py
文件中,创建一个简单的视图来添加和显示 Person 对象:from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from .models import Person
import json
@csrf_exempt
def add_person(request):
if request.method == 'POST':
data = json.loads(request.body)
person = Person(first_name=data['first_name'], last_name=data['last_name'])
person.save()
return JsonResponse({'status': 'success'})
else:
persons = list(Person.objects.all().values())
return JsonResponse(persons, safe=False)
myapp/urls.py
文件中,配置 URL:from django.urls import path
from . import views
urlpatterns = [
path('add_person/', views.add_person, name='add_person'),
]
myproject/urls.py
文件中,包含 myapp
的 URL:from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('myapp.urls')),
]
领取专属 10元无门槛券
手把手带您无忧上云