2010-02-06 91 views
2

我有兩個文件:如何使用Django將python類存儲到數據庫中?

choices.py

class SomeChoice: 
    name = u"lorem" 

class AnotherChoice: 
    name = u"ipsum" 

# etc... 

models.py

from django.db import models 
import choices 

class SomeModel(models.Model): 
    CHOICES = (
     (1, choices.SomeChoice.name), 
     (2, choices.AnotherChoice.name), 
     # etc... 
    ) 
    somefield = models.IntegerField('field', choices=CHOICES) 

問題:從choices.py類需要這樣的東西一個主鍵要存儲在我的數據庫中。在這裏我手寫這些鍵(1,2,...),但這很難看。

舉例來說,我不想這樣做:

class SomeChoice: 
    id = 1 
    name = "lorem" 

class AnotherChoice: 
    id = 2 
    name = "lorem" 

所以我的問題是:什麼是Python類存儲到數據庫中的最佳方式?

請原諒我醜陋的英語。如果您需要更多信息,請告訴我。 ;-)

回答

3

你可以使用pickle來存儲這些類的實例,但這樣會更醜陋,而你不需要來將類存儲在數據庫中,所以不要(你儘可能避免碰到數據庫)。

爲了避免在兩次地重複ID,您可以將代碼更改爲類似的東西:

choices.py

_registry = {} 

def register(choice_class): 
    id = len(_registry) + 1 
    choice_class.id = id 
    _registry[id] = choice_class 

def as_list(): 
    ret = [] 
    for id in sorted(_registry): 
     ret.append((id, _registry[id].name)) 
    return ret 

def get_choice(id): 
    return _registry[id] 

class SomeChoice: 
    name = u"lorem" 

class AnotherChoice: 
    name = u"ipsum" 

register(SomeChoice) 
register(AnotherChoice) 

models.py

from django.db import models 
import choices 

class SomeModel(models.Model): 
    somefield = models.IntegerField('field', choices=choices.as_list()) 
+0

這是一個好主意,謝謝!但是仍然存在一個問題:就你的例子而言,如果(因爲任何原因)我決定刪除'(SomeChoice)',所有(鍵,類)對都將被改變。但是我需要每個班級的*獨特*和*永久*鍵。其實問題應該是:有沒有辦法爲一個班級創建一個唯一的密鑰(自然數,非零)? – user176455 2010-02-06 16:27:29

+0

您可以調整註冊模式以將註冊表存儲在文件中,並且只有在以前從未見過類的情況下才會生成新的ID,並通過模塊名稱+名稱對類進行索引(並處理併發問題)......或者您可以在寄存器()調用上面寫'#不要碰!' – 2010-02-06 16:51:13

+0

我是一個懶惰的人,所以目前我會使用第二種選擇。非常感謝您的幫助。 :) – user176455 2010-02-06 16:59:45

0

SomeChoice和AnotherChoice類的價值是什麼?爲什麼不只是存儲(在你的SomeModel的鏈接類型的選擇),在字典中的鍵和值,並有一個新的類,它只是代表了一種選擇,

class UserChoice: 
    def __init__(self, id, name): 
     self.id = id 
     self.name = name 

,然後你會得到你的SomeChoice和AnotherChoice的相同的功能,但如果添加更多選擇,則不需要更多類。也許你的例子只是過分簡化了,但我沒有看到這些類的價值。對不起,如果我完全錯過了這一點。

相關問題