AttributeError:“ ...”对象没有属性“ *** _ set” [英] AttributeError: '...' object has no attribute '***_set'

查看:98
本文介绍了AttributeError:“ ...”对象没有属性“ *** _ set”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有

class Question(models.Model):
    created_by = models.ForeignKey(User)
    question = models.CharField(max_length=150)
    def __unicode__(self):
        return self.question

class Answer(models.Model):
    rel = models.ForeignKey(Question)
    answer = models.CharField(max_length=150)
    def __unicode__(self):
        return self.answer

,如果我这样做

answer1 = "xyz"
tmp = Question.objects.get(pk=1)
tmp.answer_set.create(answer=answer1)

我得到

AttributeError: Question对象没有属性 answer_set

AttributeError: 'Question' object has no attribute 'answer_set'

怎么了?

编辑:

或者我接下来该怎么办

更新:

main / models.py:

main/models.py:

from django import forms
from django.db import models
from django.contrib.auth.models import User

class LoginForm(forms.Form):
    username = forms.CharField(label='', widget=forms.TextInput(attrs={"placeholder":"Username"}), max_length=200)
    password = forms.CharField(label='', widget=forms.PasswordInput(render_value=False, attrs={"placeholder":"Password"}))


class SurveyForm(forms.Form):
    question = forms.CharField(label='Question', widget=forms.Textarea(attrs={"placeholder":"Type your question", "rows":6, "cols":45}), max_length=150)
    answer1 = forms.CharField(label='Answer 1', widget=forms.Textarea(attrs={"placeholder":"Type an answer option", "rows":6, "cols":45}), max_length=150)
    answer2 = forms.CharField(label='Answer 2', widget=forms.Textarea(attrs={"placeholder":"Type an answer option", "rows":6, "cols":45}), max_length=150)
    answer3 = forms.CharField(label='Answer 3', widget=forms.Textarea(attrs={"placeholder":"Type an answer option", "rows":6, "cols":45}), max_length=150)
    answer4 = forms.CharField(label='Answer 4', widget=forms.Textarea(attrs={"placeholder":"Type an answer option", "rows":6, "cols":45}), max_length=150)


class Survey(models.Model):
    created_by = models.ForeignKey(User)
    question = models.CharField(max_length=150)
    def __unicode__(self):
        return self.question


class SurveyAnswer(models.Model):
rel = models.ForeignKey(Survey)
answer = models.CharField(max_length=150)
def __unicode__(self):
    return self.answer

Traceback(最近一次通话):

Traceback (most recent call last):

File "/usr/lib/python2.6/dist-packages/django/core/handlers/base.py", line 111, in get_response
response = callback(request, *callback_args, **callback_kwargs)

File "/var/www/first/main/views.py", line 94, in NewSurvey
tmp.answer_set.create(answer=answer1)

AttributeError: 'Survey' object has no attribute 'answer_set'


<WSGIRequest
path:/new_survey/,
GET:<QueryDict: {}>,
POST:<QueryDict: {u'question': [u'xfgj'], u'answer4': [u'yfgn'], u'answer1': [u'ysfjmn'], u'answer3': [u'gfy'], u'answer2': [u'fygmn'], u'csrfmiddlewaretoken': [u'Z1GreYtKoCyMYpACbbz8yfqS72nKo0m8']}>,
COOKIES:{'csrftoken': 'Z1GreYtKoCyMYpACbbz8yfqS72nKo0m8',
'sessionid': 'cx07qf3add3c741c6f7f26b5fa5c105e'},
META:{'CONTENT_LENGTH': '120',
'CONTENT_TYPE': 'application/x-www-form-urlencoded',
'CSRF_COOKIE': 'Z0GreYtKpCyMYpAUnnq8yfBt72nKo0m8',
'DOCUMENT_ROOT': '/etc/apache2/htdocs',
'GATEWAY_INTERFACE': 'CGI/1.1',
'HTTP_ACCEPT': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'HTTP_ACCEPT_ENCODING': 'gzip, deflate',
'HTTP_ACCEPT_LANGUAGE': 'de-de,de;q=0.8,en-us;q=0.5,en;q=0.3',
'HTTP_CONNECTION': 'keep-alive',
'HTTP_COOKIE': 'csrftoken=Z0SreYtKpDvWYpACbbz5yfBt72nKo0m8;sessionid=cf07bf3add25741c6f7f26b5fa5c105e',
'HTTP_DNT': '1',
'HTTP_HOST': 'domain.tld',
'HTTP_REFERER': 'http://domain.tld/new_survey/',
'HTTP_USER_AGENT': 'Mozilla/5.0 (X11; Linux i686; rv:10.0.7) Gecko/20100101 Firefox/10.0.7 Iceweasel/10.0.7',
'PATH_INFO': u'/new_survey/',
'PATH_TRANSLATED': '/var/www/first/wsgi/new_survey/',
'QUERY_STRING': '',
'REMOTE_ADDR': '00.000.000.000',
'REMOTE_PORT': '00000',
'REQUEST_METHOD': 'POST',
'REQUEST_URI': '/new_survey/',
'SCRIPT_FILENAME': '/var/www/first/wsgi',
'SCRIPT_NAME': u'',
'SERVER_ADDR': '00.000.000.000',
'SERVER_ADMIN': '[no address given]',
'SERVER_NAME': 'domain.tld',
'SERVER_PORT': '80',
'SERVER_PROTOCOL': 'HTTP/1.1',
'SERVER_SIGNATURE': '<address>Apache/2.2.16 (Debian) Server at domain.tld Port 80</address>\n',
'SERVER_SOFTWARE': 'Apache/2.2.16 (Debian)',
'mod_wsgi.application_group': 'domain.tld|',
'mod_wsgi.callable_object': 'application',
'mod_wsgi.handler_script': '',
'mod_wsgi.input_chunked': '0',
'mod_wsgi.listener_host': '',
'mod_wsgi.listener_port': '80',
'mod_wsgi.process_group': '',
'mod_wsgi.request_handler': 'wsgi-script',
'mod_wsgi.script_reloading': '1',
'mod_wsgi.version': (3, 3),
'wsgi.errors': <mod_wsgi.Log object at 0xba725480>,
'wsgi.file_wrapper': <built-in method file_wrapper of mod_wsgi.Adapter object at 0xba717d58>,
'wsgi.input': <mod_wsgi.Input object at 0xba719c78>,
'wsgi.multiprocess': True,
'wsgi.multithread': False,
'wsgi.run_once': False,
'wsgi.url_scheme': 'http',
'wsgi.version': (1, 1)}>


推荐答案

经过测试似乎运行良好。我建议您检查您的Answer类是否引用了正确的Question类

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>
>>> 

更新:

您的反向呼叫是错误。您需要以小写形式调用模型名称,并在其后面附加_set。除非您在关系中有一个related_name参数:

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(...)

这篇关于AttributeError:“ ...”对象没有属性“ *** _ set”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆