问题
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