简体   繁体   English

'ManyToManyDescriptor' 对象在带有 PostgreSQL 的 Django 中没有属性 'add'

[英]'ManyToManyDescriptor' object has no attribute 'add' in Django with PostgreSQL

I am trying to store some data in my database, where 2 different model refer each other with 'Many-to-Many' fields.我正在尝试在我的数据库中存储一些数据,其中 2 个不同的模型使用“多对多”字段相互引用。

my models.py :我的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 :我的意见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?请建议我该如何解决这个问题?

You should add it to the questionObj , so a Questions object , not the Questions class:您应该将其添加到questionObj ,因此是Questions对象,而不是Questions类:

questionObj.correctAnsRef.add(correctAnsObj)

Note : normally a Django model is given a singular name, so Question instead of Questions .注意:通常 Django 模型被赋予一个单数名称,因此使用Question而不是Questions

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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