2011-01-20 50 views
5

我構建了一個appengine應用程序(python),該應用程序需要將整數值(100)中的現有數據存儲實體轉換爲貨幣轉換問題的浮點值(100.00)。 正確的做法如何?由於我的查詢返回錯誤,當我只是改變我的模型中的屬性類型。將IntegerProperty更改爲現有AppEngine DataStore的FloatProperty

舊型號:

class Learn(search.SearchableModel): 
    pid = db.ReferenceProperty(Product, collection_name='picks') 
    title = db.StringProperty() 
    description = db.TextProperty() 
    order = db.IntegerProperty() 
    cost = db.IntegerProperty(default=0) 
    cost1 = db.IntegerProperty(default=0) 

新型號:

class Learn(search.SearchableModel): 
    pid = db.ReferenceProperty(Product, collection_name='picks') 
    title = db.StringProperty() 
    description = db.TextProperty() 
    order = db.IntegerProperty() 
    cost = db.FloatProperty(default=0.000) 
    cost1 = db.FloatProperty(default=0.000) 

我需要一個適當的方法來改變這種數據存儲的屬性類型不改變(刪除舊的和添加新)現有數據。因爲它是許多其他表格/模型的關鍵。

感謝。

回答

12

最簡單的方法是將模型更改爲從db.Expando繼承,並從定義中刪除整數屬性。然後,加載每個實例並在每個實例上執行「instance.foo = float(instance.foo)」,然後將它們保存回數據存儲區 - 您可能需要爲此使用mapreduce API。最後,讓模型再次擴展db.Model,然後添加FloatProperties。

你真的,真的不想用浮動貨幣,雖然:浮動易受舍入錯誤,這意味着你可以失去(或獲得!)錢。相反,使用一個IntegerProperty來計算分數。

+0

再次感謝尼克,考慮整數+美分的貨幣表。 – 2011-01-20 20:06:11

0

也許一個好辦法是臨時創建新模型:

class LearnTemp(search.SearchableModel): 
    pid = db.ReferenceProperty(Product, collection_name='picks') 
    title = db.StringProperty() 
    description = db.TextProperty() 
    order = db.IntegerProperty() 
    order = db.IntegerProperty() 
    cost = db.FloatProperty(default=0.000) 
    cost1 = db.FloatProperty(default=0.000) 

然後寫一個轉換的實例從舊模式到臨時模型,將整數值浮動一些腳本,任務或視圖。確保複製ID和密鑰以及如果可能的話。

更改主模型後,將所有條目從臨時模型複製到它。然後刪除臨時模型。

這很可能不是最佳方式,並且需要一些手動遷移,儘管沒有South和應用程序引擎,我真的不覺得有一個好方法。

+0

感謝託斯滕。 – 2011-01-20 20:10:44

-1

從數據存儲管理界面編輯實體頁:

低於實體 輸入信息。如果你想改變一個 屬性的類型,將其設置爲空,保存 實體,重新編輯實體,並 更改類型

6

這裏是exampe爲的answerNick Johnson

Before

class Person(db.Model): 
    name = db.StringProperty() 
    age = db.StringProperty() #this will go to int 

After

class Person(db.Expando): 
    pass 

for person in Person.all(): 
    person.age = int(person.age) 
    person.put() 

Very after

class Person(db.Model): 
    name = db.StringProperty() 
    age = db.IntegerProperty() 
相關問題