鍍金池/ 問答/Python  HTML/ Django中如何獲取MongoDB查詢(如find())結(jié)果的某個(gè)字段值。

Django中如何獲取MongoDB查詢(如find())結(jié)果的某個(gè)字段值。

def uploadfilefiles(request):
    if request.method == 'GET':
        return HttpResponseRedirect('/uploadfilepage/')
    fileinfo = json.loads(request.POST['files'])
    client = pymongo.MongoClient('localhost', 27017)
    db = client.cloudfiledb
    filename = fileinfo["flename"]
    md5 = fileinfo["_id"]
    resu =  db[fileinfo['username'] + "fileinfo"].find({"flename": filename})
    if resu.count() == 0:
        db[fileinfo['username'] + "fileinfo"].insert(fileinfo)
        return HttpResponse(json.dumps({"Uploaded": []}))
    else:
        return HttpResponse(resu)

查詢的返回值為:
{u'username': u'mochen', u'chunkSize': 10485760, u'flename': u'hello.txt', u'length': 38, u'uploadDate': 1522581711234L, u'_id': u'-1118858670-142391418912608919631449407476'},
如何在Django中獲取某個(gè)字段的值,比如在上面的代碼else分支中,如何獲得resu的username或者其他字段,上面的返回結(jié)果是在前端瀏覽器的開發(fā)者工具的response中顯示的。

回答
編輯回答
深記你

經(jīng)實(shí)驗(yàn)及查看文檔發(fā)現(xiàn),find()函數(shù)返回的是類型為cursor的值,而find_one()返回的是數(shù)組或?qū)ο螅室L問返回的文檔的某個(gè)字段時(shí)根據(jù)使用的查詢函數(shù),若為resu = db.collection.find(),則可通過如下的方式訪問:
resu = db[username + "fileinfo"].find()

historyfilelist = []
try:
    for ele in resu:
        global historyfilelist
        historyfilelist.append(ele["filename"])
    return HttpResponse(json.dumps(historyfilelist))

若是采用的find_one()函數(shù),則可以直接通過字典訪問,(如下面的_id獲取的方式)
resu = db[fileinfo['username'] + "fileinfo"].find_one({"filename": filename})

if resu is None:
    db[fileinfo['username'] + "fileinfo"].insert(fileinfo)
    return HttpResponse(json.dumps({"Uploaded": []}))
elif resu["_id"] == md5:

上面方法親測(cè)可行。

2017年1月9日 21:47
編輯回答
愛是癌
看你的resu是什么,一般print(resu.username)或者print(resu['username']),如果是list的就是對(duì)里面的單個(gè)元素
2017年5月30日 05:41