Edit: Added possible solution and move M2M to question
I have a model where there is a many to many relationship between questions and recommendations. Each question can have many recommendations and each recommendation can apply to many questions.
Once a survey is completed the recommendations will be displayed for each question based on the risk_value.
I already have tables for question and recommendation, my question is how do I create the relationships?
Might this work:
answer_list = [1,4,9 ] #PK for answers related to question #This would be extracted from a list of lists that have the answer PKs for each question
for n = 1 to 80
question = Question.objects.get(pk = n) #Get question PK
for item in answer_list #Iterate through list of answers related to question
rec = Recommendation.get(pk= item)
question.recommendation.add(rec) #Add recommendation to question
I would define a function in the app to do that, I’m guessing I would only need o do that once and the join table would remain part of the database
class Question(models.Model):
question = models.CharField(max_length=200)
risk_value = models.IntegerField(null = True, blank=False)
q_num = models.IntegerField(null = True, blank=False)
survey = models.ForeignKey(
Surveys, on_delete=models.CASCADE, null=True
)
area = models.ForeignKey(
Area, on_delete=models.CASCADE, null=True
) # Django will store this as area_id on database
category = models.ForeignKey(
Category, on_delete=models.CASCADE, null=True
) # Django will store this as category_id on database
analysis = models.TextField(max_length=1000, default = "This would be the analysis") #Results of analysis
recommendation=recommendation.ManyToManyField(Question)
class Meta:
ordering = ['question']
def __str__(self):
return f"{self.question} Risk value is {self.risk_value}"
class Recommendation(models.Model):
recommendation = models.TextField(max_length=1000, blank = True)
def __str__(self):
return f"{self.recommendation}"