简体   繁体   English

Django Admin Manager替代

[英]Django Admin Manager Override

I have a Multiple Choice Questions, in which Model Question is Question and Choices as answers. 我有一个多项选择题,其中模型Question是问题和Choices作为答案。 I want to limit the number of Choices that can be created to a Question to 4. 我想将一个Question可以创建的Choices数量限制为4个。

A models.Manager is used to verify the number of choices for the question. 使用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)

and Choice 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()

Custom Manager 客户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

Everything works fine if I am using python shell to create Model Instances. 如果我使用python shell创建模型实例,则一切正常。

BUT: When I am using the AdminSite . 但是:当我使用AdminSite时 I am able to create more than 4 Choices to a question. 我可以为一个问题创建4个以上的选择。 How do I attain my desired behavior at AdminSite (Raise Error at Admin Site)? 如何在AdminSite上达到所需的行为(在“管理站点”上引发错误)? Override the Manager at Admin Level? 覆盖管理员级别的经理? How would I proceed that? 我将如何进行?

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

Needed To override the save method in the model class itself. 需要重写模型类本身中的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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM