我如何从views.py编辑/更改模型字段的值

时间:2019-01-29 13:52:08

标签: django django-models django-views

大家好。我想知道如何通过定义的会话列表中的项目数来更改模型字段的值

我已经制作了一个个人档案模型(用户模型是OneToOne字段) 并在“ models.py;

在view.py中,我创建了一个名为“ answer_list”的会话,该会话存储了用户提供的所有正确答案的列表。

models.py

class UserProfile(models.Model):

    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile')

    level = models.CharField(max_length=1, choices=[('Newbie', 'N'), ('Regular', 'R'), ('Expert', 'E')], default='Newbie')

views.py

def index(request):

     if 'answer_list' in request.session: #answer_list has been created previously #request.session['answer_list'] = []

        ok = request.session['answer_list']
        print (ok) #just to check the content of 'answer_list' which is correct

            if len(ok) == 4:

                user=request.user

                user.profile.level = 'R'
                user.profile.save()


    return render(request, 'index.html', {})

一旦会话“ answer_list”中的项目数达到4,我希望user.profile.level的值从“新手”更改为“常规”。

1 个答案:

答案 0 :(得分:0)

尝试

UserProfile.object.filter(user=request.user).update(level='R')