TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use meeting.set() instead. Error with Django m2m fields

TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use meeting.set() instead. Error with Django m2m fields

我是 Django 的初学者,我被 many-to-many 关系困住了。在这里,我通过日历 API 从我的 Google 日历中获取 google 会议数据。我已成功获取数据,但是当我保存会议参与者时,出现此错误:

TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use meeting.set() instead.

这是有问题的代码:

create a partcipant object & save it
  for email in participants_emails:
    participant_obj,created = Participant.objects.create(
                meeting=meeting_obj, email=participants_emails) 
    print(f'participant {participant_obj} was created==== ',created)

在这段代码中,我可以访问 participants_emails 中参与者的所有电子邮件,我要将它们保存在模型中。

下面是models.py:

from django.db import models
from django.contrib.auth.models import User 

class Meeting(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    unique_key = models.CharField(max_length=100, unique=True)
    subject = models.CharField(max_length=400, null=True, blank=True)
    start_at = models.DateTimeField(
        auto_now_add=False, auto_now=False, null=True)
    end_at = models.DateTimeField(
        auto_now_add=False, auto_now=False, null=True)
    feedback_status = models.BooleanField(null=True, default=False)

    def __str__(self):
        return self.subject

class Participant(models.Model):
    meeting = models.ManyToManyField(to=Meeting)
    email = models.EmailField(default=None, blank=True, null=True)

    def __str__(self):
        return self.email

class Question(models.Model):
    question_type = [
        ('checkbox', 'CheckBox'),
        ('intvalue', 'Integar Value'),
        ('text', 'Text'),
        ('radio', 'Radio Button'),
    ]
    question_label = models.TextField(null=True, blank=True)
    question_type = models.CharField(
        choices=question_type, default='text', max_length=80)

    def __str__(self):
        return self.question_label

class UserFeedback(models.Model):
    meeting = models.ForeignKey(Meeting, on_delete=models.CASCADE)
    participant = models.ForeignKey(Participant, on_delete=models.CASCADE)
    question = models.OneToOneField(Question, on_delete=models.CASCADE)
    question_answer = models.CharField(max_length=300, null=True, blank=True)

    def __str__(self):
        return str(self.meeting)

您不能使用 meeting=meeting_obj,因为这是一个 ManyToManyField,并且为了向 ManyToManyField 添加内容,首先两个对象都需要有一个主键。

您可以稍后将其添加到 ManyToManyField,例如:

for email in participants_emails:
    participant_obj, created = Participant.objects.get_or_create(email=participants_emails) 
    participant_obj<strong>.meeting.add(</strong>meeting_obj<strong>)</strong>
    print(f'participant {participant_obj} was created==== ',created)

您可能还想使用 get_or_create(…) [Django-doc] since create(…) [Django-doc] 而不是 return 具有 created 的二元组。