1

我正在尝试构建一个多项选择测验 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')

我只想将 in 的选择数量限制other_answersdjango-admin3 个答案。怎么做?

笔记:

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

2 回答 2

2

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

这是解决方案:

管理员.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
于 2019-06-26T02:44:14.173 回答
0

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

如果您只想将其限制为最大 3,那么您应该使用django 模型验证

于 2019-06-25T20:18:52.763 回答