7

我有

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:“问题”对象没有属性“答案集”

怎么了?

编辑:

或者我接下来可以做些什么来解决这个问题......或者有没有其他选择?

更新:

主/模型.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

回溯(最近一次通话最后):

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)}>
4

3 回答 3

6

经过测试,似乎工作正常。如果您的 Answer 类引用了正确的 Question 类,我建议您检查导入

>>> 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 参数:

tmp.surveryanswer_set.create(...)
于 2012-12-12T22:01:54.133 回答
4

请注意,如果型号名称由多个单词组成,则需要将其写在一起,不要下划线。例如Enterprise模型有很多ContactPerson模型

enterprise.contactperson_set

并不是

enterprise.contact_person_set

这就是我的情况出错的原因。

于 2016-06-10T09:51:02.473 回答
2

这也是初学者的条件

b = Book.objects.all() 这是返回书籍列表,所以 不起作用 b.writer_set.all()

Use b = Book.objects.get(id=90) //用这个只获取一个对象然后尝试
b.writer_set.all()

于 2015-02-11T13:55:06.367 回答