【问题标题】:What does it mean for an object to be unscriptable?对象不可编写脚本意味着什么?
【发布时间】:2011-06-04 19:09:05
【问题描述】:

我不知道这里发生了什么...我只想检查模型字段的值,然后相应地对其进行更新...感谢任何帮助或见解!

型号:

class UserProfile(models.Model):
    user = models.ForeignKey(User, unique=True)
    beta = models.CharField(max_length=1, blank=True, null=True)

查看:

from internal.accounts.models import UserProfile
from django.contrib.auth.models import User
@login_required    
def beta_testers(request):
    user = User.objects.get(username=request.user.username)
    user_profile = user.get_profile()

    count = UserProfile.objects.filter(beta='1').count()

    if count < 50 and not user_profile['beta']:
        user_profile['beta'] = '1'
        user_profile.save()

错误:

TypeError at /utilities/beta-signup/
'UserProfile' object is unsubscriptable
Request Method: GET
Request URL:    http://localhost/utilities/beta-signup/?x=1&y=15
Django Version: 1.2.1
Exception Type: TypeError
Exception Value:    
'UserProfile' object is unsubscriptable
Exception Location: C:/django\internal\cms_helper\views.py in beta_testers, line 284

【问题讨论】:

标签: django django-models django-views


【解决方案1】:

错误是“不可订阅”。您的 user_profile 对象不是字典。使用user_profile.beta,而不是user_profile['beta']

【讨论】:

  • 哦,是的,一定是这个。谢谢。
  • 为什么会这样呢?有没有办法让 Django 提供该功能?
【解决方案2】:

或者,您可以使用带有getattr 的字符串:

getattr(user_profile, 'beta', False)

False 是默认值;在您的情况下,它可以检查该值是否已设置。我发现这很有帮助,所以我想我会发布这个解决方案,即使这个问题是几年前提出的。 :)

【讨论】:

    【解决方案3】:

    方法一

    model_name.object.filter(column_name='value').last
    

    方法二

    当您尝试在文本字段中插入模型对象时会发生此错误

    【讨论】:

      猜你喜欢
      • 2010-09-18
      • 1970-01-01
      • 2011-04-05
      • 2023-02-10
      • 2014-02-08
      • 2013-08-30
      • 2020-06-01
      • 2012-10-10
      相关资源
      最近更新 更多