安装依赖
pip install mongoengine==0.18.2
在 setting.py
中配置mongodb数据库
# 将默认数据库设置为none
DATABASES = {
# 'default': {
# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
# }
'default': {
'ENGINE': None,
}
}
# 连接mongodb数据库
from mongoengine import connect
connect('bdyl', host='127.0.0.1', port=27017)
建立基于mongo数据库的model
from django.db import models
from mongoengine import *
class BaiduData(Document):
search_value = StringField(required=True)
time = DateTimeField(required=True)
location = StringField()
video_top1 = ListField()
audio_top1 = ListField()
video_list = ListField()
audio_list = ListField()
qa_list = ListField()
article_list = ListField()
meta = {
'collection':'BaiduData'
}
增加数据
@api_view(['GET', 'POST'])
def get_bdyl_index(request):
result = ''
keyword = request.GET.get('keyword','')
result = getData(keyword)
result['time'] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
# 存入 mongoDB
baidudata = BaiduData(
search_value=keyword,
time=result['time'],
video_top1=result['video_top1'],
audio_top1=result['audio_top1'],
video_list= result['video_list'],
audio_list= result['audio_list'],
qa_list=result['qa_list'],
article_list=result['article_list'],
)
baidudata.save()
return HttpResponse(json.dumps(result), content_type="application/json")
删改查
# 查
result = StudentModel.objects.filter(name='水痕')
print(result[0].age)
# 改
result = StudentModel.objects.filter(name='水痕').first().update(name='张三')
print(result)
# 删
result = StudentModel.objects.filter(name='张三').first().delete()
print(result)