AttributeError: '…' object has no attribute '***_set'

放肆的年华 提交于 2019-12-05 06:47:10

Tested it out seems to be working fine. I would suggest you to check you imports if your Answer class is referencing to the right Question class

>>> from demo.models import *
>>> q = Question.objects.create(created_by=User.objects.get(id=1), question='test')
>>> q
<Question: test>
>>> q.answer_set.create(answer='test answer')
<Answer: test answer>
>>> 

Update:

Your reverse call is wrong. You need to call the model name in small caps and append _set to it. Unless, you have a related_name argument in the relationship:

tmp.surveryanswer_set.create(...)

Note that in case of model name consists of multiple words, you need to write it together, without underscores. For example for Enterprise model has many ContactPerson models

enterprise.contactperson_set

and not

enterprise.contact_person_set

That was the reason of error in my case.

This is also condition for beginners

b = Book.objects.all() this is return a list of Books so b.writer_set.all() not work

Use b = Book.objects.get(id=90) //use this to get only one object and then try
b.writer_set.all()

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!