2015-12-07 100 views
0

我有一個選擇題,其中Question是問題,Choices是答案。我想將可創建的Choices的數量限制爲Question爲4.Django Admin Manager覆蓋

A models.Manager用於驗證問題選項的數量。

class Question(models.Model): 
    QUESTION_TYPES = (
    ('MC', 'Multiple Choice'), 
    ('SB', 'Subjective'), 
    ) 
    question_type = models.CharField(choices=QUESTION_TYPES, max_length=2, default='MC') 
    question_text = models.TextField(null=False, blank=False) 

Choice

class Choice(models.Model): 
    choice_text = models.CharField(max_length=100, null=True) 
    question= models.ForeignKey(Question, null=True , related_name='choices') 
    is_answer = models.BooleanField(default=False) 
    objects = ChoiceManager() 

定製Manager

class ChoiceManager(models.Manager): 
    def create(self, **kwargs): 
     question = kwargs.pop('question',None) 
     if question is not None: 
      if question.choices.all().count() > 4: # see related_name 
       raise AssertionError 
      else: 
       return self 

一切,如果我使用Python Shell中創建模型實例工作正常。

但是:當我使用AdminSite。我能夠爲一個問題創建4個以上的選擇。我如何在AdminSite上實現自己想要的行爲(在管理站點發生錯誤)?在管理員級別覆蓋管理器?我將如何繼續?

admin.site.register(Question) 
admin.site.register(Choice) 

回答

0

需要覆蓋模型類本身的save方法。

class Choice(models.Model): 
    choice_text = models.CharField(max_length=100, null=True) 
    question= models.ForeignKey(Question, null=True , related_name='choices') 
    is_answer = models.BooleanField(default=False) 
    objects = ChoiceManager() 

    def save(self, *args, **kwargs): 
     if self.question.choices.all().count() > 4: 
      print "You Shall Not Save" 
      raise ValueError 
     else: 
      print "Super Method Called" 
      super(Choice, self).save(*args, **kwargs) 
相關問題