我在Django Users
和Contexts
中有两个模型。我定义了以下模型
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请求中的action字段添加上下文。如您所见,在Contexts
模型中,字段users
与{ {1}}模型。但是,当我尝试将值保存到User
时,出现以下错误
Contexts table
基于this StackOverflow post,我尝试执行以下操作:
Context saving exception Direct assignment to the forward side of a many-to-many set is prohibited. Use users.set() instead.
但是我仍然收到相同的错误。我在做什么错了?
答案 0 :(得分:3)
错误应该很清楚;您不能直接分配给多对多字段。创建项目后执行此操作。
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"))
还请注意,您无需在save()
或添加m2m值之后调用create()
。