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

标签 django django-models django-views

当我试图将一个属性与另一个具有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/

相关文章:

python - 如何在 Heroku Django 上安装 PyMuPDF

Django issubclass() arg 1 must be a class error in insering TabularInline at admin 页面

django - 是否可以在不重新启动 Django 的情况下重新加载 View ?

python - 在 Django 中保存 ModelForm 时,如何将用户模型作为ForeignKey 值传递?

python - Django 2、python 3.4 无法解码 urlsafe_base64_decode(uidb64)

sql - 如何让 Django QuerySet 'exclude' 正常工作?

python - lambda - 'QuerySet' 对象没有属性 'xxx'

django - 在 pip 安装 uWSGI 之后没有/etc/uwsgi/directory - 我如何使用启用应用程序?

python - 如何使用 GeoIP2() django 模型从 IP 地址调用中提取保存的信息以显示在我的 html 中

python - Django 在创建后设置模型字段