亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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

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

千萬里不及你 2019-05-22 16:54:36
defuploadfilefiles(request):ifrequest.method=='GET':returnHttpResponseRedirect('/uploadfilepage/')fileinfo=json.loads(request.POST['files'])client=pymongo.MongoClient('localhost',27017)db=client.cloudfiledbfilename=fileinfo["flename"]md5=fileinfo["_id"]resu=db[fileinfo['username']+"fileinfo"].find({"flename":filename})ifresu.count()==0:db[fileinfo['username']+"fileinfo"].insert(fileinfo)returnHttpResponse(json.dumps({"Uploaded":[]}))else:returnHttpResponse(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中獲取某個字段的值,比如在上面的代碼else分支中,如何獲得resu的username或者其他字段,上面的返回結果是在前端瀏覽器的開發者工具的response中顯示的。
查看完整描述

2 回答

?
波斯汪

TA貢獻1811條經驗 獲得超4個贊

經實驗及查看文檔發現,find()函數返回的是類型為cursor的值,而find_one()返回的是數組或對象,故要訪問返回的文檔的某個字段時根據使用的查詢函數,若為resu=db.collection.find(),則可通過如下的方式訪問:resu=db[username+"fileinfo"].find()
historyfilelist=[]
try:
foreleinresu:
globalhistoryfilelist
historyfilelist.append(ele["filename"])
returnHttpResponse(json.dumps(historyfilelist))
若是采用的find_one()函數,則可以直接通過字典訪問,(如下面的_id獲取的方式)resu=db[fileinfo['username']+"fileinfo"].find_one({"filename":filename})
ifresuisNone:
db[fileinfo['username']+"fileinfo"].insert(fileinfo)
returnHttpResponse(json.dumps({"Uploaded":[]}))
elifresu["_id"]==md5:
上面方法親測可行。
                            
查看完整回答
反對 回復 2019-05-22
?
長風秋雁

TA貢獻1757條經驗 獲得超7個贊

看你的resu是什么,一般print(resu.username)或者print(resu['username']),如果是list的就是對里面的單個元素
                            
查看完整回答
反對 回復 2019-05-22
  • 2 回答
  • 0 關注
  • 828 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號