Django 抛出"禁止直接分配给多对多集合的前端"错误



我在DjangoUsersContexts中有两个模型。我已将模型定义如下

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

现在我收到一个包含以下 JSON 的 POST 请求

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

我想在Contexts表中创建一条记录。以下是我正在尝试做的事情

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 请求中的操作字段添加上下文。如您所见,在Contexts模型中,字段usersUser模型具有多对多关系。但是当我尝试将值保存到Contexts table时,我收到以下错误

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

基于这篇StackOverflow帖子,我尝试做这样的事情:

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

相关内容

  • 没有找到相关文章

最新更新