如何删除 Django 中的多对多关系?

how to delete many-to-many relations in django?

我正在尝试删除我的 m2m 关系,我想我写对了,但是在数据库中没有任何反应,网站上也没有任何反应

这是我的models.py

class Department(models.Model):

    id = models.AutoField(primary_key=True)
    department = models.CharField(max_length=60)
    info_grafana = models.TextField()
    users = models.ManyToManyField(User)

和我的views.py

class ViewUserAccount(View):
    def post(self, request, id_account: int, *args, **kwargs):

        if request.POST.get('_method') == 'delete':
            self.delete(request, id_account)
        else:
            self.create(request, id_account)
        
        return redirect(request.META.get('HTTP_REFERER'))


    def delete(self, request, id_account):

        id_direction = request.POST.get('direction_id')
        id_project = request.POST.get('project_id')

        if id_project:
            project = Project.objects.get(id=id_project)
            project.users.remove(User.objects.get(id=id_account))

        elif id_direction:
            direction = Department.objects.get(id=id_direction)
            direction.users.remove(User.objects.get(id=id_account))

我想从 department/project 中删除用户的要点,但没有任何反应:(

这就是我从前端得到的

<QueryDict: {'csrfmiddlewaretoken': ['Fa3C0uuP4dlsrvSr1zkvD9UiovRnid7JYYRPRSksNsm0cLXCFPs4ROT0k2M7nv2E'], '_method': ['delete'], 'id_project': ['1'], 'id_direction': ['68']}>

您在尝试获取参数时似乎有错字(前端正在发送 id_projectid_direction 但您正在尝试获取 project_iddirection_id).要解决它只需更改:

def delete(self, request, id_account):
    id_direction = request.POST.get('id_direction')
    id_project = request.POST.get('id_project')
    ...