У меня есть две модели в 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')
Теперь я получаю запрос POST, который содержит приведенный ниже JSON.
{
"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
поле users
имеет отношение многие ко многим с моделью User
. Но когда я пытаюсь сохранить значения в 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"))
Но я все еще получаю ту же ошибку. Что я делаю не так?