0

我在 models.py 中有一个购物车应用程序:

def get_all_models():
    tup = []
    for ct in ContentType.objects.filter(app_label__in=['shoppingcart','products','productoptions']):
        if ct is not None:
            mclass = ct.model_class()
            if mclass is not None:
                tup.append((mclass.__module__+'.'+mclass.__name__,mclass.__name__))
    return tuple(tup)

class ConditionSet(models.Model):
    model_name      = models.CharField(max_length=50, choices = get_all_models()) 
    model_attribute = models.CharField(max_length=50)
    operator        = models.CharField(max_length=50, choices=OPERATORS)
    val             = models.CharField(max_length=50,null=True,blank=True)
    evaluation      = models.NullBooleanField(null=True, blank=True)
    def get_all_models():
        tup = []
        for ct in ContentType.objects.filter(app_label__in=['shoppingcart','products','productoptions']):
            if ct is not None:
                mclass = ct.model_class()
                if mclass is not None:
                    tup.append((mclass.__module__+'.'+mclass.__name__,mclass.__name__))
        return tuple(tup)
    def evaluate(self):
        app_label = str(self.model_name.split('.')[0])
        model_name = str(self.model_name.split('.')[2])
        model = get_model(app_label= app_label, model_name = model_name)
    def __str__(self):
        return self.model_attribute

在 admin.py 我只注册了模型

我发现我的 def get_all_models() 产生两组不同的输出,当从 shell 运行时我有这个

get_all_models() (('shoppingcart.models.Cart', 'Cart'), ('shoppingcart.models.CartItem', 'CartItem'), ('shoppingcart.models.CartRule', 'CartRule'), ('products. models.CasesAccessory', 'CasesAccessory'), ('productoptions.models.Coating', 'Coating'), ('shoppingcart.models.ConditionSet', 'ConditionSet'), ('products.models.Eyeglass', 'Eyeglass' ), ('products.models.GiftVoucher', 'GiftVoucher'), ('productoptions.models.Lens', 'Lens'), ('productoptions.models.Prescription', 'Prescription'), ('products.models. Readingglass', 'Readingglass'), ('products.models.Sunglass', 'Sunglass'), ('productoptions.models.Tint', 'Tint'), ('productoptions.模型.愿景','愿景'))

当它调用填充选择时,我失去了第一个选择,即第一个选项,即 conetenttype cart 将 model_class() 提供为 None,而在 shell 上工作时它找到了 model_class()?需要一些解释。

4

1 回答 1

2

当 Django 验证它的模型时,你的代码就会被执行。因此,Cart可能尚未经过验证,它的模型类是None.

我建议不要在模型定义中设置选项,我之前遇到过一些麻烦。相反,我建议稍后动态填充它们,例如当您实例化表单时。

于 2013-02-11T13:59:33.620 回答