我们的models.py中有一个类:
class Score(model.Model):
score = models.IntegerField()
当答案是正确的时候,我们想要调用得分对象并在views.py中更新它:
def answer(request, level_id):
# next three lines are working for us.
o = Level.objects.get(id=level_id)
guess = request.GET.get('guess', '').strip()
correct = o.answers.filter(value__iexact=guess).exists()
b = Score.objects.get('score')
b.score += o.points
b.save()
我们仍然没有使用if
语句运行b.score + = o.points,因为首先我想知道我们是否可以更新b.score。
class Level(model.Models):
points = models.IntegerField("Point Value')
我们得到的错误是:
ValueError at /answer/1 too many values to unpack
答案 0 :(得分:0)
试试这个!
def answer(request, level_id):
# next three lines are working for us.
o = Level.objects.get(id=level_id)
guess = request.GET.get('guess', '').strip()
correct = o.answers.filter(value__iexact=guess).exists()
b = Score.objects.get(score)
b.score += int(o.points)
b.save()
更新时,您缺少保存对象。
b.save() # should save it
答案 1 :(得分:0)
您必须指定要尝试查询的Score实例。
假设您之前创建了一个,并且它具有主键1,您可以使用以下方法访问它:
b = Score.objects.get(pk=1)
或者,如果是第一次,你可以运行:
b, created = Score.objects.get_or_create(pk=1)
如果您刚创建 created
将是真的