Django DatabaseError“用作表达式的子查询返回的多行”对象的可编辑相关字段

时间:2013-08-05 22:52:07

标签: database django

我正在尝试为我的模板添加内联,但继续收到数据库错误:

 more than one row returned by a subquery used as an expression

我的models.py中有3个对象相互关联。用户将能够看到选择了哪个教师,并且列出了该教师下的所有所有者(教师和所有者将仅显示为不可编辑的列表)。我想让所有者下的所有宠物都列出并可编辑。有关我收到此错误的原因的任何想法?我怎么能够实现我的目标呢?

models.py

class Teacher(models.Model):
        teacher = models.CharField(max_length=300)

class Owner(models.Model):
       relevantteacher = models.ForeignKey(Teacher)     
       owner = models.CharField(max_length=300)

class PetName(models.Model):
        relevantowner = models.ForeignKey(Owner)
        pet_name = models.CharField(max_length=50)

forms.py

class OwnerForm(forms.ModelForm):
    class Meta:
       model = Owner

PetNameFormSet = inlineformset_factory(Owner,
    PetName,
    can_delete=False,
    extra=3,
    form=OwnerForm)

views.py

def petname(request, teacher_id):
   teacher = get_object_or_404(Teacher, pk=teacher_id)

   owners = Owner.objects.filter(relevantteacher=teacher_id)

   if request.method == "POST":
      petNameInlineFormSet = PetNameFormSet(request.POST, request.FILES, instance=owners)

      if petNameInlineFormSet.is_valid():
         petNameInlineFormSet.save()

         return HttpResponseRedirect(reverse('success'))

   else:
      petNameInlineFormSet = PetNameFormSet(instance=owners) //error might be here?

   context = {'teacher': teacher, 'owners': owners, 'petNameInlineFormSet' : petNameInlineFormSet}
   return render(request, 'petname.html', context)

更新

这是追溯:

File "hde/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  111.  response = callback(request, *callback_args, **callback_kwargs)
File "/views.py" in petname
  60.  petNameInlineFormSet = PetNameFormSet(instance=owners)
File "lib/python2.7/site-packages/django/forms/models.py" in __init__
  697.  queryset=qs, **kwargs)
File "lib/python2.7/site-packages/django/forms/models.py" in __init__
  424.  super(BaseModelFormSet, self).__init__(**defaults)

2 个答案:

答案 0 :(得分:1)

只需要将1个对象传递给实例

owner = owners[0]

然后

instance=owner

但是,我一次只能添加/编辑宠物名称1所有者。 感谢aamir的帮助!

答案 1 :(得分:0)

我相信您的错误位于views.py文件的第二行。我相信当您尝试在模板中指定get_object_or_404时,调用teacher.id方法会导致错误。对get_object_or_404方法的调用从数据库返回多行,因此无法从多行调用teacher.id