gpt4 book ai didi

django - TypeError : Direct assignment to the forward side of a many-to-many set is prohibited. 请改用 meeting.set()。 Django m2m 字段出错

转载 作者:行者123 更新时间:2023-12-05 03:37:27 24 4
gpt4 key购买 nike

我是 Django 的初学者,我被多对多关系所困扰。在这里,我通过日历 API 从我的谷歌日历中获取谷歌 session 数据。我已成功获取数据,但是当我保存 session 参与者时,出现此错误:

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]create(…) [Django-doc]不返回带有 created 的二元组。

关于django - TypeError : Direct assignment to the forward side of a many-to-many set is prohibited. 请改用 meeting.set()。 Django m2m 字段出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69314934/

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