gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 11:38:47 24 4
gpt4 key购买 nike

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

现在我收到一个包含以下 JSON 的 POST 请求
{
"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 请求中的 action 字段添加上下文。如您所见,在 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.

基于 this StackOverflow post ,我尝试做这样的事情:
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"))

另请注意,您不需要拨打 save()之后 create()或添加 m2m 值。

关于Django 抛出 'Direct assignment to the forward side of a many-to-many set is prohibited.' 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51011540/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com