首页 > 解决方案 > 即使输入值不同,Django 也会从 MongoDB 给出相同的响应

问题描述

我最近开始使用 Django。

我已经使用 PyMongo 模块 [pip3 install pymongo] 集成了 MongoDB。

我的问题:

即使在数据库更新后,Django 也会给我相同的数据。每当我进行一些操作时;就像将用户输入的电子邮件与数据库中现有的电子邮件 ID 进行比较一样,我每次都会得到相同的结果。

看起来结果正在被缓存。

网址.py

from django.urls import path
from . import views

urlpatterns = [
    path('', views.homepage),
    path('register/', views.register),
]

视图.py

from django.shortcuts import render
from pymongo import MongoClient
from django import http

def homepage(request):
    return (render(request, 'index.html'))

def register(request):

    if request.method == 'POST':
        name = request.POST['name']
        email = request.POST['email']
        password = request.POST['password']

        client = MongoClient('mongodb://my_ip:27017/')
        db = client.trainingdb
        collection = db.data
        emailCheck = str(collection.find({"Email":email}))
        if emailCheck == "":
            dbData = {
            'Name': name,
            'Email': email,
            'Password': password
            }
            collection.insert_one(dbData)
            return http.HttpResponse("Success!")
        else:
            return http.HttpResponse("Email exists in database!")
    else:
        return render(request, 'register.html')

homepage方法适用于索引页或主页。该register方法用于注册页面。

在这里,我试图检查用户输入的电子邮件 ID 是否预先存在于数据库中。

测试用例:

第一次,我输入了一个已经在数据库中的电子邮件 ID,我得到了预期的结果:Email exists in database!.

但是第二次,我输入了一个不在数据库中的电子邮件 ID;但我得到相同的旧结果:Email exists in database!

是由于缓存还是类似的原因?

标签: pythondjangomongodbmongodb-querypymongo

解决方案


collection.find()返回一个 Cursor 实例。出于某种原因,您将其转换为字符串并将其与"". 但是,即使列表是空str()的,也不会是"",而是类似于"<pymongo.cursor.Cursor object at 0x7f10b69d0c50>"。所以条件永远不成立。

没有理由转换为字符串或与字符串进行比较。相反,检查匹配的文档数量:

emailCheck = collection.find({"Email":email}).count()
if emailCheck == 0:
    ...

推荐阅读