my problem is the following. I have two models in the database, which I link together using a ManyToMany relationship. For the admin page I currently use “admin.TabularInline” to bind different objects to one via the graphic. I still want to specify an order in the connections, preferably numbers which represent an order for processing. A bit more figuratively described I have the model “Survey” and the model “SurveyQuestion”. So I connect many SurveyQuestions with the Survey. But I can’t specify an order, because I don’t have an additional field for it. It is not known before how many questions will be in a survey. Nor is it known which questions will be inserted. Usually they are built during the compilation of the survey and may be used later for another survey. I am grateful for every tip!
Advertisement
Answer
This can be achieved by defining a custom relationship table between the Survey and SurveyQuestion using through argument. For example you can define a relationship model:
class Question(models.Model): question = models.CharField(max_length=256) class Survey(models.Model): name = models.CharField(max_length=256) questions = models.ManyToManyField(Questions, through='Questionnaire') class Questionnaire(models.Model): survey = models.ForeignKey(Survey, on_delete=models.CASCADE) question = models.ForeignKey(Question, on_delete=models.CASCADE) question_order = models.IntegerField()
The details and example can be found here: https://docs.djangoproject.com/en/3.1/topics/db/models/#extra-fields-on-many-to-many-relationships. If you do not want to mess up with the models, then you have to find out some hack like was proposed by Ronak Muhta.