使用视图更新列表中的模型字段时出现问题。更新仅在列表中的第一项中运行,但在其他项中不运行,但如果我在shell中运行,则更新所有对象。
models.py
class Contrato(models.Model):
nome = models.CharField(u'Nome/Identificação', max_length=200)
num = models.CharField(u'Número', max_length=200, blank=True, null=True)
data_inicio = models.DateField(u'Data do início')
data_fim = models.DateField(u'Data do fim', editable=False, blank=True, null=True)
progress = models.IntegerField(u'progresso',editable=False, max_length=100, blank=True, null=True)
...
views.py
def index(request):
vigentes = Contrato.objects.all()
vigentes_total = Contrato.objects.filter(status='0').order_by('nome').count()
h = datetime.date.today()
print vigentes
for v in vigentes:
d = v.data_fim - v.data_inicio
dif = h - v.data_inicio
v.progress = int((float(dif.days) / float(d.days))*100)
v.save()
template = loader.get_template('contratos/index.html')
context = RequestContext(request, {
'vigentes': vigentes,
})
if not request.user.is_authenticated():
return HttpResponse("You are not logged in.")
else:
return HttpResponse(template.render(context))
有什么想法解决这个问题?
编辑。
如果我将视图更改为:
def index(request):
vigentes = Contrato.objects.all()
print vigentes
for item in vigentes:
print item
template = loader.get_template('contratos/index.html')
context = RequestContext(request, {
'vigentes': vigentes,
'vigentes_total': vigentes_total,
})
if not request.user.is_authenticated():
return HttpResponse("You are not logged in.")
else:
return HttpResponse(template.render(context))
我只看到第一项。问题是视图中的for循环。