2013-02-11 29 views
0

我有這個在models.py的購物車應用:contenttype.model_class()是NoneType

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我只註冊了模型

,我發現我的高清get_all_models()產生兩個不同組的輸出,從殼 運行時我有此

get_all_models( )('shoppingcart.models.Cart','Cart'),('shoppingcart.models.CartItem','CartItem'),('shoppingcart.models.CartRule','CartRule'),('products.models ('productsAccessory','CasesAccessory'),('productoptions.models.Coating','Coating'),('shoppingcart.models.ConditionSet','ConditionSet'),('products.models.Eyeglass','Eyeglass') ,('products.models.GiftVoucher','GiftVoucher'),('productoptions.models.Lens','Lens'),('productoptions.models.Prescription','處方'),('products.models.Readingglass ','Readingglass'),('products.models.Sunglass','Sunglass'),('productoptions.models.Tint','Tint'),('productoptions.models.Vision','Vision'))

其中當我i ts被調用來填充選項,我放棄了第一個選擇, 第一個選項,即conetenttype cart將model_class()設置爲None,而在shell上工作時找到model_class()?需要一些解釋。

回答

2

當Django驗證它的模型時,您的代碼正在執行。因此,Cart可能還沒有被驗證,它的模型類是None

我建議不要在模型定義中設置選項,我以前遇到過一些麻煩。相反,我建議稍後動態填充它們,例如當你實例化一個表單。