E TypeError:禁止直接分配到多对多集的前向端。使用 subject.set() 代替
我正在编写一些 api 调用的测试,我遇到的问题是我无法弄清楚如何在 Django 中分配多对多变量(主题)。
models.py
class Subject(BaseModel):
id = models.AutoField(primary_key=True)
name = models.TextField(null=False, blank=False)
answers = models.ManyToManyField("registration.Answer", through="AnswerSubject")
class Answer(BaseModel):
id = models.AutoField(primary_key=True)
text = models.TextField(null=False, blank=False)
subjects = models.ManyToManyField("subjects.Subject", through="subjects.AnswerSubject")
test.py
def tets_get_answer:
Answer.objects.create(
text=f'{"test answer"}',
subjects = f{"test subject"} # the error is here, how do I assign subjects?
),
........
这是我收到的错误:
E TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use subjects.set() instead.
Any help is appreciated
I am writing a test to some api calls, the issue that I am getting is that I can't figure out how to assign a many-to-many variable(subjects) in Django.
models.py
class Subject(BaseModel):
id = models.AutoField(primary_key=True)
name = models.TextField(null=False, blank=False)
answers = models.ManyToManyField("registration.Answer", through="AnswerSubject")
class Answer(BaseModel):
id = models.AutoField(primary_key=True)
text = models.TextField(null=False, blank=False)
subjects = models.ManyToManyField("subjects.Subject", through="subjects.AnswerSubject")
test.py
def tets_get_answer:
Answer.objects.create(
text=f'{"test answer"}',
subjects = f{"test subject"} # the error is here, how do I assign subjects?
),
........
this is the error that I am getting:
E TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use subjects.set() instead.
Any help is appreciated
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您创建一个
Subject
模型,并在稍后进行设置:但是,没有理由定义
ManyToManyField
两次:如果您在 Django 中定义一个关系,Django 也会自动定义一个关系相反。您可以使用lated_name=…
参数 [Django-doc]:You create a
Subject
model, and set it later:There is however no reason to define the
ManyToManyField
twice: if you define a relation in Django, Django will automatically also define a relation in reverse. You can specify the name of that reverse relation with therelated_name=…
parameter [Django-doc]: