我是django的新手,我正在尝试使用get_or_create模型函数,但即使我的模型中有属性,我也会收到错误
AttributeError at /professor/adicionar-compromisso
'tuple' object has no attribute 'dias'
Request Method: POST
Request URL: http://localhost:8000/professor/adicionar-compromisso
Django Version: 1.4.1
Exception Type: AttributeError
Exception Value:
'tuple' object has no attribute 'dias'
Exception Location: c:\htdocs\rpv\GerenDisponibilidade\professor\models.py in inserirCompromisso, line 63
Python Executable: C:\Python27\python.exe
Python Version: 2.7.3
Python Path:
['c:\\htdocs\\rpv\\GerenDisponibilidade',
'C:\\Python27\\lib\\site-packages\\distribute-0.6.27-py2.7.egg',
'C:\\Python27\\lib\\site-packages\\pip-1.1-py2.7.egg',
'C:\\Python27\\lib\\site-packages\\sphinx-1.1.3-py2.7.egg',
'C:\\Python27\\lib\\site-packages\\docutils-0.9.1-py2.7.egg',
'C:\\Python27\\lib\\site-packages\\jinja2-2.6-py2.7.egg',
'C:\\Python27\\lib\\site-packages\\pygments-1.5-py2.7.egg',
'C:\\Windows\\system32\\python27.zip',
'C:\\Python27\\DLLs',
'C:\\Python27\\lib',
'C:\\Python27\\lib\\plat-win',
'C:\\Python27\\lib\\lib-tk',
'C:\\Python27',
'C:\\Python27\\lib\\site-packages',
'C:\\Python27\\lib\\site-packages\\setuptools-0.6c11-py2.7.egg-info']
Server time: Seg, 3 Set 2012 17:57:17 -0300
模型
class DiaSemana(models.Model):
DIAS_CHOICES = (
("Seg", "Segunda-Feira"),
("Ter", "Terça-Feira"),
("Qua", "Quarta-Feira"),
("Qui", "Quinta-Feira"),
("Sex", "Sexta-Feira"),
("Sab", "Sábado"),
("Dom", "Domingo"),
)
dias = models.CharField(max_length=20, choices=DIAS_CHOICES)
这里我试图搜索是否存在现有值,否则创建新的并保存
for diaSemana in diaSemanas:
d = DiaSemana.objects.get_or_create(dias=diaSemana)
d.dias = diaSemana;
d.save()
c.save()
c.diaSemana.add(d);
怎么了?
答案 0 :(得分:37)
get_or_create
不只是返回对象:
返回
(object, created)
的元组,其中object是检索或创建的对象,并且创建的是一个布尔值,指定是否创建了新对象。
在您的情况下,d
已被分配此元组而不是您期望的对象,因此您将获得属性错误。您可以通过将代码更改为:
d, created = DiaSemana.objects.get_or_create(dias=diaSemana)
以下两行看起来对我来说没用。上面的get_or_create
调用可确保d.dias=diaSemana
,因此无需再次分配。也许没有必要拨打save
。
d.dias = diaSemana;
d.save()
答案 1 :(得分:2)
文档明确指出get_or_create会返回元组(对象,已创建) - 这正是您所看到的错误。 https://docs.djangoproject.com/en/dev/ref/models/querysets/#get-or-create
答案 2 :(得分:2)
而不是:
dias = models.CharField(max_length=20, choices=DIAS_CHOICES)
做的:
dias = models.CharField(max_length=20, choices=DIAS_CHOICES)[0]
正如@Alasdair所说,元组中的第一个是对象