[英]How can I get data from a mongodb collection using pymongo in django using get method?
I have one mongodb database and I have connected that db with pymongo in django. 我有一个mongodb数据库,我在django中将该数据库与pymongo连接起来。 I am new to django, I am trying to get if the entered data present in the collection or not, if present return that record using get method
我是django的新手,如果输入的数据存在于集合中,我试图获取,如果存在,则使用get方法返回该记录
import pymongo
from pymongo import MongoClient
db_name = 'student_db'
client = MongoClient('localhost', 27017)
db_obj = client[db_name]
collection=db_obj['mongo_app_student']
@api_view(['GET'])
def test(request):
data = request.data
for x in collection.find():
if data in x:
print('entered a right value')
return Response(data)
TypeError at /test unhashable type: 'dict' 在/ test unhashable类型的TypeError:'dict'
I am getting this error when i am trying to get the output in postman. 当我试图在邮递员中获取输出时,我收到此错误。 please help
请帮忙
First you Should use a POST request for that and since find() return a cursor, you're trying to iterate on a cursor. 首先你应该使用POST请求,因为find()返回一个游标,你试图迭代一个游标。 I'm not sure that's a good idea.
我不确定这是个好主意。 And assuming
request.data
is a dict() try using ==
for comparison with x
假设
request.data
是一个dict()尝试使用==
与x
进行比较
Also Try casting what you get from mongo in a list like this : 还尝试在这样的列表中转换从mongo获得的内容:
import pymongo
from pymongo import MongoClient
db_name = 'student_db'
client = MongoClient('localhost', 27017)
db_obj = client[db_name]
collection=db_obj['mongo_app_student']
@api_view(['GET', 'POST'])
def test(request):
response_data = None
if request.method == 'POST':
for x in list(collection.find()):
if data == x:
print('entered a right value')
response_data = data
return Response(response_data )
Let me know how it goes. 让我知道事情的后续。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.