2013-04-05 132 views
0

在我的應用程序中,我包含一個名爲xml解析的函數。我試圖從xml文件中數據數據並將其保存到mysql數據庫。解析xml到mysql數據庫

我在google引擎的幫助下編寫了這段代碼,但是根據需要,數據並沒有保存在數據庫中。我可以運行該應用程序而沒有任何錯誤。

請參考下面

views.py

def goodsdetails(request): 
    path = "{0}shop.xml".format(settings.PROJECT_ROOT) 
    xmlDoc = open(path, 'r') 
    xmlDocData = xmlDoc.read() 
    xmlDocTree = etree.XML(xmlDocData) 

    for items in xmlDocTree.iter('item'): 
     item_id = items[0].text 
    customername = items[1].text 
     itemname = items[2].text 
     location = items[3].text 
     rate = items[4].text   
     shop=Shop.objects.create(item_id=item_id,customername=customername, 
      itemname=itemname,location=location,rate=rate) 
     shop.save() 


shops = Shop.objects.all() 
    context={'shops':shops} 
    return render(request,'index.html', context) 

我的代碼我使用上述邏輯來保存從XML file.I在數據庫中的數據我沒有得到任何錯誤,但它不節能進入數據庫

預計的答案是最受歡迎的。

* 更新: *我更新的代碼,真正的XML數據被保存在數據庫,但同時顯示相同的我得到以下回溯

IntegrityError at/
(1062, "Duplicate entry '101' for key 'PRIMARY'") 

感謝

回答

0

Shop.objects.get負荷來自數據庫的數據。你想要創建數據,你只需要調用Shop(item_id=item_id,customername=customername, itemname=itemname,location=location,rate=rate)然後shop.save()

如果你想更新的數據,你需要做的是這樣的:

shop = Shop.objects.get(tem_id=item_id) 
shop.customername = customername 
...etc... 
shop.save() 
+0

使用Shop.objects.create()餘did't它和檢查,但如上面一樣是不給任何錯誤,但不保存在分貝,任何sugesstions是受歡迎的 – 2013-04-05 06:10:02

+0

@MonkL:那麼也許你可以用你實際嘗試過的代碼更新問題?因爲你問題中的代碼不會創建數據。 – 2013-04-05 06:19:04

+0

我更新了我的錯誤和查看代碼 – 2013-04-05 06:31:39