2012-03-13 70 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

相关问题