I am trying to store some data in my database, where 2 different model refer each other with 'Many-to-Many' fields.
my models.py
:
class CorrectAns(models.Model):
ansId = models.IntegerField(primary_key=True)
responseText1 = models.TextField(null=True, blank=True)
isDeleted = models.BooleanField(default=False)
questionRef = models.ManyToManyField('Questions')
class Questions(models.Model):
questionId = models.IntegerField(primary_key=True)
groupId = models.IntegerField(default=0)
questionTitle = models.TextField()
correctAnsRef = models.ManyToManyField(CorrectAns, related_name="questionReletedResponses")
my views.py
:
for i in QuestionsList:
questionObj = Questions(
questionId = i['Id'],
groupId = i['GroupId'],
questionTitle = i['QuestionTitle'],
)
questionObj.save()
for j in i['Responses']:
correctAnsObj = CorrectAns.objects.create(
ansId = j['Id'],
responseText1 = myResponseText1,
isDeleted = j['IsDeleted'],
)
correctAnsObj.questionRef.add(questionObj)
correctAnsObj.save()
Questions.correctAnsRef.add(correctAnsObj)
return
now it shows error with line:
Questions.correctAnsRef.add(correctAnsObj)
Like:
'ManyToManyDescriptor' object has no attribute 'add'
Please suggest how can I fix this?
CodePudding user response:
You should add it to the questionObj
, so a Questions
object, not the Questions
class:
questionObj.correctAnsRef.add(correctAnsObj)
Note: normally a Django model is given a singular name, so
Question
instead of.Questions