mommomonthewind
mommomonthewind

Reputation: 4650

How to define a relation N:N in python3+django2?

I am following this tutorial: https://docs.djangoproject.com/en/2.0/intro/tutorial02/

In this tutorial, I can create a class Question and a class Choice. One question contains multiple choices, but one choice belongs to only 1 question.

So following the tutorial, there is a foreign_key in the class Choice that refers to the class Question, and the variable choice_set will be automatically created.

Now I want to modify that a choice can belong to multiple questions as well. How should I do that?

Upvotes: 2

Views: 33

Answers (1)

ascripter
ascripter

Reputation: 6233

Instead of

question = models.ForeignKey(Question, on_delete=models.CASCADE)

you will use a ManyToManyField:

question = models.ManyToManyField(Question, on_delete=models.CASCADE)

Please read yourself through the docs and play around with it to learn :)

Upvotes: 2

Related Questions