1

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

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

10 Comments

Now I am getting this error:Expected a Response, HttpResponse or HttpStreamingResponse to be returned from the view, but received a <class 'NoneType'>
Yes the return statement shouldn' t be in the if statement. I've updated my answer above, try that out and let me know how it goes
Thanks! this working pretty good but when running this server on postman, I am giving key=data, Value={'firstname':'Abburi'}. I am not getting anything like I have firstname:Abburi lastname:jagadeesh student_id:1 in my collection
Hum, are you trying to send a data like {"firstname":"Abburi", "lastname":"jagadeesh"} and you want your service to check if that exist in mongo ? if yes return that same data ?
Exactly if that present return me that doccument/row
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.