django - get() 返回了多个主题 [英] django - get() returned more than one topic

查看:37
本文介绍了django - get() 返回了多个主题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

When I tried to relate an attribute with another one which has an M to M relation I received this error:

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

get() returned more than one topic -- it returned 2!

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

Can you guys tell me what that means and maybe tell me in advance how to avoid this error ?

模型

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() returned more than one topic -- it returned 2!

上述错误表示您在使用get()

The above error indicatess that you have more than one record in the DB related to the specific parameter you passed while querying using get() such as

Model.objects.get(field_name=some_param)

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

To avoid this kind of error in the future, you always need to do query as per your schema design. In your case you designed a table with a many-to-many relationship so obviously there will be multiple records for that field and that is the reason you are getting the above error.

因此,您应该使用 filter() 将返回多条记录.比如

So instead of using get() you should use filter() which will return multiple records. Such as

Model.objects.filter(field_name=some_param)

请在此处阅读有关如何在 django 中进行查询的信息.

Please read about how to make queries in django here.

这篇关于django - get() 返回了多个主题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆