2012-03-13 49 views
0

我有一個Django模型,我需要持有一個可調用的對象(在這種情況下是對另一個模型的引用),以便將其與一些「條件」一起存儲,以便將來應用於該模型。如何在django模型中保存可調用對象?

我的辦法是,像這樣:

MODEL_CHOICES = (
    (django.contrib.auth.models.User, 'User'), 
    [some more] 
    ) 
class Model: 
    chosen_model = models.IntegerField(choices=MODEL_CHOICES) 
    conditions = models.TextField() 

條件將是這個樣子:

{'status': 1, [some other]} 

但顯然

django.contrib.auth.models.User
是不是一個有效的整數。

我嘗試才達到如下: 呼叫

chosen_model.objects.filter(**conditions) 
在視圖

。 這甚至可能嗎?如果是的話,我需要什麼樣的字段來存儲對模型的引用?

非常感謝!

回答

2

我建議你在這裏使用ContentType模型。

from django.contrib.contenttypes.models import ContentType 

class YourModel: 
    chosen_model = models.ForeignKey(ContentType) 
    conditions = models.TextField() 
+0

+1完美的答案,我不知道ContentType,似乎很有用。謝謝! – Subito 2012-03-13 17:08:10

2

看起來你可能需要一個外鍵content type

+0

+1這看起來和我想要的完全一樣! – Subito 2012-03-13 17:07:06

相關問題