How can i Edit/Change the value of a model field from views.py

倾然丶 夕夏残阳落幕 提交于 2021-02-05 08:39:07

问题


Good-day everyone. I want to know how i can change the value of a model-field through the number of items in a defined sessions list

I have already made a profile model (which is OneToOne Field to the user model) with a 'level' field as shown below in my models.py;

And in view.py, I have created a session called 'answer_list' which is a list that stores all correct answers provided by the user.

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', {})

I want the value of the user.profile.level to change from 'Newbie' to 'Regular' once the number of items in the session 'answer_list' gets to 4. Please how can i go about it


回答1:


Try this:

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


来源:https://stackoverflow.com/questions/54422620/how-can-i-edit-change-the-value-of-a-model-field-from-views-py

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!