Reputation: 17
I have one mongodb database and I have connected that db with pymongo in django. 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
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'
I am getting this error when i am trying to get the output in postman. please help
Upvotes: 1
Views: 953
Reputation: 148
First you Should use a POST request for that and since find() return a cursor, you're trying to iterate on a cursor. I'm not sure that's a good idea. And assuming request.data
is a dict() try using ==
for comparison with x
Also Try casting what you get from mongo in a list like this :
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.
Upvotes: 1