Search code examples
pythondjangomanytomanyfield

How to save many to many relations


I want to save the many to many relations, but I get this error:

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'))

how should i solve this problem?

That is what I get from frontend:

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

Solution

  • You should add it like this.

    Change this line like this.

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

    Check this out to better understanding.

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