【问题标题】:How to limit number of choices of a ManyToManyField to a specific number of choices如何将 ManyToManyField 的选择数量限制为特定数量的选择
【发布时间】:2019-11-07 16:42:27
【问题描述】:

我正在尝试构建一个多项选择测验 Django 应用程序。我有一个名为Answer 的模型,还有一个名为Question 的模型。

这里是Answer的内容:

class Answer(models.Model):
    text = models.CharField(max_length=255)

这是Question

class Question(models.Model):
    text = models.CharField(max_length=255)
    correct_answer = models.ForeignKey('Answer', on_delete=models.CASCADE, related_name='correct_answers')
    other_answers = models.ManyToManyField('Answer')

我想将django-adminother_answers 的选择数量限制为3 个答案。该怎么做?

注意事项:

  1. 我可以重新建模我的模型。
  2. 我不会使用django-forms,我只是为移动应用构建一个API。

【问题讨论】:

    标签: django django-admin django-modeladmin


    【解决方案1】:

    感谢Geoff Walmsley 的回答,它启发了我的正确答案。

    这是解决方案:

    admin.py

    from django.contrib import admin
    from django.core.exceptions import ValidationError
    from .models import Question
    from django import forms
    
    
    class QuestionForm(forms.ModelForm):
        model = Question
    
        def clean(self):
            cleaned_data = super().clean()
            if cleaned_data.get('other_answers').count() != 3:
                raise ValidationError('You have to choose exactly 3 answers for the field Other Answers!')
    
    
    @admin.register(Question)
    class QuestionAdmin(admin.ModelAdmin):
        form = QuestionForm
    

    【讨论】:

      【解决方案2】:

      如果您想将其限制为 3 个具体答案,我认为您可以使用 limit_choices_to

      如果您只想将其限制为最多 3 个,那么您应该使用 django model validation

      【讨论】:

      • 感谢您的贡献。我希望 other_answers 正好是 3 个答案。我尝试了您的解决方案,但失败了,因为在保存记录之前调用了 clean 函数,这意味着 self.other_answers.count() 始终为零。但是,您的回答启发了我正确的答案。如果您想了解如何操作,请阅读我的回答。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多