出现“无属性”错误时如何添加到ManyToMany?

时间:2019-11-10 23:51:30

标签: django manytomanyfield

使用表格,在尝试获取要添加的问题的查询集之后,我试图将项目添加到questions对象的多方字段Quiz中。我保存了ModelForm,但是当我添加项目时,出现AttributError:'function' object has no attribute 'questions'

以前,我能够在模型中使用保存方法create a Quiz object with 3 random questions。但是,我看不到仅使用模型从特定查询集中添加3个问题的方法

views.py

def choose(request, obj_id):
    """Get the id of the LearnObject of interest"""
    """Filter the questions and pick 3 random Qs"""
    my_qs = Question.objects.filter(learnobject_id=obj_id)
    my_qs = my_qs.order_by('?')[0:3]
    if request.method == 'POST':
        form = QuizForm(request.POST)
        if form.is_valid():
            new_quiz = form.save
            for item in my_qs:
                new_quiz.questions.add(item)
            new_quiz.save()
            return HttpResponseRedirect('/quizlet/quiz-list')
    else:
        form = QuizForm()  
    return render(request, 'quizlet/quiz_form.html', {'form': form})

和models.py

class LearnObject(models.Model):
    """model for the learning objective"""
    code = models.CharField(max_length=12)
    desc = models.TextField()

class Question(models.Model):
    """model for the questions."""
    name = models.CharField(max_length=12)
    learnobject = models.ForeignKey(
        LearnObject, on_delete=models.CASCADE,
        )
    q_text = models.TextField()
    answer = models.CharField(max_length=12)

class Quiz(models.Model):
    """quiz which will have three questions."""
    name = models.CharField(max_length=12)
    questions = models.ManyToManyField(Question)
    completed = models.DateTimeField(auto_now_add=True)
    my_answer = models.CharField(max_length=12)

class QuizForm(ModelForm):
    """test out form for many2many"""
    class Meta:
        model = Quiz
        fields = ['name', 'my_answer']

错误发生在第new_quiz.questions.add(item)行。我不明白这一点,因为Quiz的模型具有一个字段questions,并且该对象(我认为)已经在第一个new_quiz = form.save()

上创建了

1 个答案:

答案 0 :(得分:1)

错误在下一行:new_quiz = form.save,您缺少(),将其更改为new_quiz = form.save()

如果没有,则将函数form.save的引用保存到new_quiz,而不是函数返回的对象。