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

标签 django django-models django-views

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

我已经制作了一个个人资料模型(这是用户模型的 OneToOne Field) 在我的 models.py 中带有一个“level”字段,如下所示;

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

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

一旦 session “answer_list”中的项目数达到 4,我希望 user.profile.level 的值从“新手”更改为“常规”。请问我该怎么做

最佳答案

试试这个:

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

关于django - 我如何从views.py编辑/更改模型字段的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54422620/

相关文章:

python - 认证用户Django取决于用户

Django Postgres 错误,字段 "is not of a character type"

django - 在 Django 中,如何防止 "Save with update_fields did not affect any rows."错误?

python - 创建参加事件选项按钮的最有效方法[Django/Python]?

python - html模板中的条件

python - 通过 urlopen 打开远程文件并将其添加到 FileField

python - Node js vs Django vs Flask用于从python流式传输多个视频

django - django 的 bulk_create 是原子的吗?

python - 如何在模板中显示数据库中的数据

python - Django 框架中未使用值(在范围内未使用)