2010-11-26 94 views
1

這是一個模型的一個非常簡化的版本,我的工作:處理是基於其他領域的Django模型領域的要求

class ClothingTop(models.Model): 

    SWEATER = 0 
    SHIRT = 1 

    TOP_CHOICES = (
     (SWEATER, 'Sweat shirt'), 
     (SHIRT, 'Shirt'), 
    ) 

    name = models.CharField(max_length=32) 
    type = models.PositiveSmallIntegerField(choices=TOP_CHOICES) 
    hoodie = models.BooleanField(default=False) 
    buttons = models.PositiveSmallIntegerField(null=True, blank=True) 

    def __unicode__(self): 
     return self.name 

    @property 
    def type_text(self): 
     if self.type == self.SWEATER: 
      if self.hoodie: 
       return 'Hooded sweatshirt' 
      return 'Plain sweatshirt' 
     elif self.type == self.SHIRT: 
      return 'Shirt' 

我想要求buttons如果type設置爲SHIRT 。我的第一個想法是重寫save方法,但我不確定這是否是實現這一點的最明智的方法。

任何人有任何建議嗎?

回答

1

簡單建議,而且我相信這是在實踐中最好的一個,是你創造一個ClothingTopModelForm和設置,將做自定義驗證表單上的buttons_clean()方法。這種形式也必須設置爲ClothingTopModelAdmin

唯一的另一種方法是爲buttons字段創建一個自定義模型字段(驗證器在此處不起作用,因爲它們只獲取按鈕字段值並且不知道類型和其他模型字段)。做到這一點最簡單的方法是:

ButtonsField(models.PositiveSmallIntegerField): 

    def validate(self, value, model_instance): 
     # here we get the buttons field value and can get the type value 
     # exactly what we need! 

     type = getattr(model_instance, 'type') 

     if type == SHIRT and not value: 
      raise ValidationError('Type set to shirt, but buttons value is empty') 

     super(self, ButtonsField).validate(value, model_instance) 

我所提到的自定義字段中的方法對完整性的考慮,我認爲你應該跳過創建自定義字段類型除非這是完全通用的,容易重複使用在任何模型。對於這些特殊情況,只需使用表單驗證。您的模型應該只確保數據庫的完整性,您已經完全覆蓋了ClothingTop,業務規則從表單驗證中冒出來。

+0

有了這個解決方案,我還必須爲管理員應用程序提供正確的表單嗎? – 2010-11-27 01:12:11