简体   繁体   中英

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?

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 :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM