从 Views.py 更新模型字段

Jul*_*ian 2 python django django-models django-forms django-views

我有一种感觉,我在这里遗漏了一些明显的和相关的语法,所以我提前道歉。

当用户成功处理表单时,我试图更新用户的状态。

# Models.py
class Account(AbstractBaseUser):
    status_list = ( ('R',"RED"), ('B',"BLUE"), ('G',"GREEN"),)
    status = models.CharField(max_length=1, choices=status_list, default='R')
    value = models.CharField(max_length=30, unique=False, blank=True)



#Forms.py
class Form(forms.ModelForm):

    class Meta:
        model = Account
        fields = ('value', )



# Views.py
def View(request):

    if request.POST:
        form = Form(request.POST, instance=request.user)
        if form.is_valid():
            form.initial = {"value": request.POST['value'],}
            form.save()
            # Here is the issue V
            Account.objects.filter(
            status=Account.status).update(status='B')
            return redirect('status')
Run Code Online (Sandbox Code Playgroud)

我已经尝试过这两篇文章中提出的解决方案:

1. 从 Views.py 编辑模型字段

2. 对象没有属性“update”

以及许多其他随机且极具创意的组合。

有人知道这个调用的正确语法吗?

Mar*_*rkL 5

Account.objects.filter()将返回QuerySet而不是 Account 对象。您需要使用get(),或者filter()[0]您知道该帐户存在;如果您不确定它是否存在,您可以使用get_or_create()

如果您想更新当前用户的特定帐户状态,您需要做的是:

第 1 步:获取您要更新的帐户

# you can get it by searching from Account
account = Account.objects.get(user=request.user)
# or you can can it directly from the request.uer
account = request.user.account
Run Code Online (Sandbox Code Playgroud)

第 2 步:更新字段

account.status = 'B' # set it to whatever you want to update
account.save() # you need to use save() because there is no update() in a model object

Run Code Online (Sandbox Code Playgroud)

  • 万一将来有人使用它作为参考:我认为您直接从 request.user 调用的方法非常出色,但实际上我只需要调用 a = request.user 因为 Account 本身没有作为属性。感谢您的帮助 (2认同)