当我试图将一个属性与另一个具有M 到M 关系的属性相关联时,我收到此错误:
get() returned more than one topic -- it returned 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()
returned more than one topic -- it returned 2!
上述错误表明您在使用 get()
查询时传递的特定参数相关的数据库中有多个记录。比如
Model.objects.get(field_name=some_param)
为避免将来出现此类错误,您始终需要根据您的模式设计进行查询。 在您的情况下,您设计了一个带有 many-to-many relationship 的表所以显然该字段会有多个记录,这就是您收到上述错误的原因。
因此,您应该使用 filter()
而不是使用 get()
这将返回多个记录。比如
Model.objects.filter(field_name=some_param)
请阅读如何在 Django 中进行查询 here .
关于django - get() 返回了多个主题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22063748/