如何保存多对多关系

How to save many to many relations

我想保存多对多关系,但出现此错误:

Direct assignment to the forward side of a many-to-many set is prohibited. Use users.set() instead.

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 get(self, request, id_account: int, *args, **kwargs) -> render:
        
        return render(request, 'settings/UserAccount.html', {
            'title': f'Аккаунт пользователя {request.user}',
            'account': User.objects.get(id=id_account),
            'direction': Department.objects.all()
        })

    def post(self, request, id_account, *args, **kwargs):

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

        if id_direction:
            direction = Department.objects.get(id=id_direction)
            direction.users = User.objects.get(id=id_account)
            direction.save()


        if id_project:
            pass

        return redirect(request.META.get('HTTP_REFERER'))

我该如何解决这个问题?

这就是我从前端得到的:

<QueryDict: {'csrfmiddlewaretoken': ['G1P0UIxoATVsTLM7hGnmWT7z1GyTskrZIr0svdKTQfrsH67zW2OAiCO0kAvLHPuC'], 'direction_id': ['7'], 'project_id': ['']}>

你应该这样添加。

像这样更改此行。

direction.users.add(User.objects.get(id=id_account))

检查 this 以更好地理解。

>>> a2 = Article(headline='NASA uses Python')
>>> a2.save()
>>> a2.publications.add(p1, p2)
>>> a2.publications.add(p3)