添加ManytoManyField会破坏Django

时间:2014-03-26 02:37:41

标签: python django

在我的项目中,我有一个模型Project,当保存时会创建另一个模型Access,其中包含manytomanyfield,access_list,用户可以将其他用户作为协作者添加到他们的项目中。它工作 - 当我创建一个新项目时,我可以添加其他用户,但如果我添加第二个用户,它将不再提供错误的页面,

Exception Value: get() returned more than one Access -- it returned 2!"

如果我切换到我已添加到项目中的帐户,然后使用该帐户添加其他用户,则会添加正常并且不会破坏页面。

当页面中断时,它还会在我的“项目”页面上创建项目的其他实例,即使数据库中只有一个项目实例。

我的代码:

Models.py:

class Project(models.Model):
    created_by = models.ForeignKey(User)

    super(Project, self).save()
    Access.objects.get_or_create(project=self)

class Access(models.Model):
    project = models.ForeignKey(Project)
    access_list = models.ManyToManyField(User)
    pubdate = models.DateTimeField(default=timezone.now)

Views.py:

@login_required 
def access(request, project_id=1):
thisuser = request.user
if Access.objects.filter(Q(access_list=thisuser) | Q(project__created_by=thisuser), project__id=project_id).exists():
        accesspermission = Access.objects.filter(Q(access_list=thisuser) | Q(project__created_by=thisuser), project__id=project_id).order_by('-project__project_pubdate')[0]
    else:
        accesspermission = None
    if Entry.objects.filter(project_id=project_id).exists():
        anyentries = Entry.objects.filter(project_id=project_id, entry_unique=1).order_by('-entry_pubdate')[0]
    else:
        anyentries = None
    if Entry.objects.filter(project_id=project_id, entry_unique=1).exists():
        firstentry = Entry.objects.filter(project_id=project_id, entry_unique=1).order_by('-entry_pubdate')[0]
    else:
        firstentry = None
    if Entry.objects.filter(project_id=project_id).exists():
        lastentry = Entry.objects.filter(project_id=project_id).order_by('-entry_pubdate')[0]
        lastentrynumber = lastentry.entry_unique
    else:
        lastentrynumber = None
if request.method == "POST":    
    form = AddAccessForm(request.POST)
    if form.is_valid():
        p = form.save(commit=False)

        adduserfromform = p.accessupdate
        if User.objects.filter(username=adduserfromform).exists():
            usertoadd = User.objects.get(username=adduserfromform)
            projecttoadd = Access.objects.filter(project__id=project_id).order_by('-project__project_pubdate')[0]
            projecttoadd.access_list.add(usertoadd)
        else:
            usertoadd = None

        removeuserfromform = p.accessremove
        if User.objects.filter(username=removeuserfromform).exists():
            usertoremove = User.objects.get(username=removeuserfromform)
            projecttoremove = Access.objects.filter(project__id=project_id).order_by('-project__project_pubdate')[0]
            projecttoremove.access_list.remove(usertoremove)
        else:
            usertoremove = None

        form.save()

        return HttpResponseRedirect('/projects/get/%s/access' % project_id)

回溯:

Traceback (most recent call last):
  File "/webapps/filmeditdb/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 114, in get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/webapps/filmeditdb/local/lib/python2.7/site-packages/django/contrib/auth/decorators.py", line 22, in _wrapped_view
    return view_func(request, *args, **kwargs)
  File "/webapps/filmeditdb/filmeditdb/docproject/views.py", line 284, in access
    def access(request, project_id=1):
  File "/webapps/filmeditdb/local/lib/python2.7/site-packages/django/db/models/manager.py", line 151, in get
    return self.get_queryset().get(*args, **kwargs)
  File "/webapps/filmeditdb/local/lib/python2.7/site-packages/django/db/models/query.py", line 310, in get
    (self.model._meta.object_name, num))
MultipleObjectsReturned: get() returned more than one Access -- it returned 2!
2014-03-25 22:48:26 [17264] [INFO] Handling signal: winch
2014-03-25 22:48:26 [17264] [INFO] SIGWINCH ignored. Not daemonized

1 个答案:

答案 0 :(得分:0)

通常会建议添加完整的回溯,但是从显示的错误中可能出现问题:

projecttoremove = Access.objects.get(project__id=project_id).order_by('-project__project_pubdate')[0]

Djangos get() 始终期望返回 1个对象。如果有0个对象,如果超过0,则抛出DoesNotExist异常,抛出MultipleObjectsReturned异常。

更改该行以匹配此处的前一行:

projecttoadd = Access.objects.filter(project__id=project_id).order_by('-project__project_pubdate')[0]

如果失败,请确定错误的电话。您获得的例外情况非常明确。 在代码中的某个时刻,您使用一些参数调用Access.objects.get()并且它正在找到2个对象而不是1.修复参数,或者可以将其切换为使用filter()