我在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','镜头'),('productoptions.models.Prescription','处方'),('products.models.Readingglass', 'Readingglass'),('products.models.Sunglass','Sunglass'),('productoptions.models.Tint','Tint'),('productoptions.models.Vision','Vision'))
当它被称为填充选择时,我放弃了第一选择, 第一个选项是,conetenttype cart将model_class()设为None,而在shell上工作时它会找到model_class()?需要一些解释。
答案 0 :(得分:2)
当Django验证它的模型时,您的代码正在执行。因此,Cart
可能尚未经过验证,其模型类为None
。
我建议不要在模型定义中设置选项,之前我遇到过一些麻烦。相反,我建议稍后动态填充它们,例如当您实例化表单时。