django-get()返回了多个主题

当我尝试将一个属性与另一个具有M对M关系的属性相关时,我收到此错误:

get()返回了多个主题-返回2!

你们能告诉我这是什么意思,也许可以提前告诉我如何避免此错误?

楷模

class LearningObjective(models.Model):

learning_objective=models.TextField()

class Topic(models.Model):

learning_objective_topic=models.ManyToManyField(LearningObjective)

topic=models.TextField()

输出 LearningObjective.objects.all()

[<LearningObjective: lO1>, <LearningObjective: lO2>, <LearningObjective: lO3>]

输出 Topic.objects.all()

[<Topic: Topic object>, <Topic: Topic object>, <Topic: Topic object>, <Topic: Topic object>, <Topic: Topic object>, <Topic: Topic object>, <Topic: Topic object>, <Topic: Topic object>, <Topic: Topic object>, <Topic: Topic object>, <Topic: Topic object>, <Topic: Topic object>, <Topic: Topic object>, <Topic: Topic object>]

意见

 def create_themen(request):

new_topic=Topic(topic=request.POST['topic'])

new_topic.save()

return render(request, 'topic.html', {'topic': topic.objects.all()})

def create_learning_objective(request):

new_learning_objective=LearningObjective(learning_objective=request.POST['learning_objective'])

new_learning_objective.save()

new_learning_objective_topic=Topic.objects.get(topic=request.POST['topic'])

new_learning_objective_topic.new_learning_objective_topic.add(new_learning_objective)

return render( request, 'learning_objective.html', {

'topic': Topic.objects.all(),

'todo': TodoList.objects.all(),

'learning_objective': LearningObjective.objects.all()

})

回答:

get() 返回了多个主题-返回了2个!

上面的错误表明你在数据库中有多个记录,这些记录与你使用get()诸如

Model.objects.get(field_name=some_param)

为了避免将来发生此类错误,你始终需要根据架构设计进行查询。在你的情况下,你设计了一个具有多对多关系的表,因此显然该字段将有多个记录,这就是你收到上述错误的原因。

因此,get()应使用filter()它将返回多个记录而不是使用。如

Model.objects.filter(field_name=some_param)

以上是 django-get()返回了多个主题 的全部内容, 来源链接: utcz.com/qa/416637.html

回到顶部