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

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

>Solution :

You create a Subject model, and set it later:

def tets_get_answer(self):
    answer = Answer.objects.create(
        text='test answer',
        # no subjects
        # …
    )
    subject = Subject.objects.create(
        name='test subject'
    )
    answer.subjects.add(subject)

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 the related_name=… parameter [Django-doc]:

class Subject(BaseModel):
    name = models.TextField()
    # no answers


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

Leave a Reply