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

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

我正在为一些 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

您创建了一个 Subject 模型,稍后进行设置:

def test_get_answer(self):
    <strong>answer</strong> = Answer.objects.create(
        text='test answer',
        # <strong>no</strong> subjects
        # …
    )
    <strong>subject</strong> = Subject.objects.create(
        name='test subject'
    )
    <strong>answer</strong>.subjects.add(<strong>subject</strong>)

然而没有理由定义 ManyToManyField 两次:如果你在 Django 中定义一个关系,Django 也会自动定义一个相反的关系。您可以使用 related_name=… parameter [Django-doc]:

指定反向关系的名称
class Subject(BaseModel):
    name = models.TextField()
    # <strong>no</strong> answers


class Answer(BaseModel):
    text = models.TextField()
    subjects = models.ManyToManyField(
        Subject,
        through='subjects.AnswerSubject',
        <strong>related_name='answers'</strong>
    )