django取資料庫資料轉成list或者字典dict

來源:互聯網
上載者:User

標籤:pat   lis   引號   info   inf   處理   url   pen   通過   

問題:

想將從資料庫取出的資料轉成自己想要的格式。

取出的資料是QuerySet對象

info = testcase_info.objects.filter(id=db_id)取出的不是對象,不能直接取到表中具體欄位的值。

info = testcase_info.objects.get(id=db_id)通過get可以直接取到對象,然後後面就輕鬆了。

還有注意的是,取到的欄位資料都是str類型的,想要變成list或者dict都需要自己再做處理。下面代碼是一個處理的例子:

ls = []
info = testcase_info.objects.get(id=db_id)
url = info.url
path_type = info.path_type.replace("‘", "").strip("[]").strip().split(‘,‘)//去掉空格和[]以及單引號,並以逗號分隔後產生一個list。
path = info.path.replace("‘", "").strip("[]").strip().split(‘,‘)
do_type = info.do_type.replace("‘", "").strip("[]").strip().split(‘,‘)
do = info.do.replace("‘", "").strip("[]").strip().split(‘,‘)
for i in range(len(path_type)):
my_data = {path_type[i]: path[i], do_type[i]: do[i]}//組裝成一個字典。
ls.append(my_data)//把字典放進一個大的list中給後面程式使用。

django取資料庫資料轉成list或者字典dict

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.