【问题标题】:Updating Model Field from Views.py从 Views.py 更新模型字段
【发布时间】:2020-08-11 14:29:35
【问题描述】:

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

我正在尝试在用户成功处理表单后更新他们的状态。

# 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')

我已经尝试了这两个帖子中提出的解决方案:

1. Editing model field from Views.py

2. Object has no attribute 'update'

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

有没有人碰巧知道这个调用的正确语法?

【问题讨论】:

  • 您显示的代码或您所做的任何其他尝试到底有什么问题?
  • 在当前状态下,我没有收到错误消息,但状态未更新。
  • 我认为您在更新状态后错过了保存帐户。

标签: python django django-models django-forms django-views


【解决方案1】:

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

第 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

【讨论】:

  • 以防将来有人将其用作参考:我认为您直接从 request.user 调用的方法很棒,但实际上我只需要调用 a = request.user 因为 Account 没有自己作为属性。感谢您的帮助
【解决方案2】:

您需要将更改保存到Account 实例,例如

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()

          a = Account.objects.get(user=request.user)
          a.update(status='B') 
          # or
          #a.status = 'B'
          a.save()
          return redirect('status')

正如@MarkLiang 指出的那样,filter 返回一个 QuerySet,而不是单个 Account 的实例。

【讨论】:

    猜你喜欢
    • 2019-06-22
    • 1970-01-01
    • 1970-01-01
    • 2020-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-10
    • 2019-04-06
    相关资源
    最近更新 更多