Django 抛出 'Direct assignment to the forward side of a many-to-many set is prohibited.' 错误

Django throws 'Direct assignment to the forward side of a many-to-many set is prohibited.' error

我在 Django 中有两个模型 UsersContexts。我定义的模型如下

class User(models.Model):
    userId = models.PositiveIntegerField(null = False)
    pic = models.ImageField(upload_to=getUserImagePath,null=True)
    Email = models.EmailField(null = True)

class Contexts(models.Model):
    context_name = models.CharField(max_length=50)
    context_description = models.TextField()
    context_priority = models.CharField(max_length=1)
    users = models.ManyToManyField(User, related_name='context_users')

现在我收到一个 POST 请求,其中包含以下内容 JSON

{
"user" : 12,
"action" : "add",
"context_name": "Network debug",
"context_description" : "Group for debugging network issues",
"context_priority": "L"
}

我想在 Contexts 中创建一条记录 table.Below 是我正在尝试做的事情

from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse
import json
from .models import *
import json


@csrf_exempt
def context_operation(request):
    if request.method == "POST":
        user_request = json.loads(request.body.decode('utf-8'))
        try:
            if user_request.get("action") == "add":
                conv = Contexts.objects.create(
                    context_name=user_request.get("context_name"),
                    context_description=user_request.get("context_description"),
                    context_priority=user_request.get("context_priority"),
                    users=user_request.get("user")
                )
                conv.save()
        except Exception as e:
            print("Context saving exception", e)
            return HttpResponse(0)
        return HttpResponse(1)

我在这里尝试添加一个基于 JSON request.As 中的操作字段的上下文,你可以看到,在 Contexts 模型中,字段 usersUser model.But 有多对多关系 当我尝试将值保存到 Contexts table 时,我收到以下错误

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

基于,我试过这样做:

users=User.objects.add(user_request.get("user"))

但我仍然收到同样的错误。我做错了什么?

错误应该很清楚;您不能直接分配给多对多字段。创建项目后执行此操作。

conv = Contexts.objects.create(
    context_name=user_request.get("context_name"),
    context_description=user_request.get("context_description"),
    context_priority=user_request.get("context_priority"),
)
conv.users.add(user_request.get("user"))

另请注意,您无需在 create() 或添加 m2m 值后调用 save()