问题描述
当我尝试将属性与另一个具有 M到M 关系的属性相关联时,我收到此错误:
When I tried to relate an attribute with another one which has an M to M relation I received this error:
你能告诉我这是什么意思可能提前告诉我如何避免这个错误?
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( )
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)
为了避免今后出现这种错误,您总是需要根据架构设计进行查询。
在您的情况下,您设计了一个具有 M2M 关系的表格,显然会出现该字段的多个记录,这就是您收到上述错误的原因。
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 M2M relationship so obviously there will be multiple records for that field and that is the reason you are getting the above error.
所以不要使用 get()
,您应该使用 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()返回多个主题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!