TypeError 'x' 对象没有属性 '__getitem__'

Posted

技术标签:

【中文标题】TypeError \'x\' 对象没有属性 \'__getitem__\'【英文标题】:TypeError 'x' object has no attribute '__getitem__'TypeError 'x' 对象没有属性 '__getitem__' 【发布时间】:2012-10-15 23:24:56 【问题描述】:

我得到了错误

'CampSite' object has no attribute '__getitem__'

当我在管理界面中保存一个新的 CampCon 条目时。我有一个名为 campsites 的应用程序来处理露营地的数据库,我还有另一个名为 content 的应用程序来处理评论。我对 Django 很陌生,这是我的第一个非教程项目。我一直在绞尽脑汁在网上搜索答案,但没有运气。预先感谢您的帮助。 这是我的露营地模型:

from django.contrib.gis.db import models

class CampSite(models.Model):
    name = models.CharField(max_length=250)
    showers = models.BooleanField()
    flush = models.BooleanField()
    rv = models.BooleanField()
    lonlat = models.PointField(null=True, blank=True)

    objects = models.GeoManager()

    def __unicode__(self):
        return self.name

这是内容模型:

from django.contrib.gis.db import models
from campsites.models import CampSite
from django.contrib.auth.models import User
from activities.models import Activities


class CampCon(models.Model):
    campsite = models.ForeignKey(CampSite)
    trip = models.ForeignKey('Trip')
    Date = models.DateField()
    user = models.ForeignKey(User)
    overall_review = models.TextField()
    facilities_review = models.IntegerField()
    things_to_do = models.IntegerField()
    privacy = models.IntegerField()
    beauty = models.IntegerField()
    overall_rating = models.IntegerField()

    def __unicode__(self):
        return self.campsite

class ImageDB(models.Model):
    campsite = models.ForeignKey(CampSite)
    user = models.ForeignKey(User)
    description = models.CharField(max_length=200)
    image = models.ImageField(upload_to='/home/bobby/Pictures/CampThat')
    date_uploaded = models.DateField()
    date_taken = models.DateField()
    trip = models.ForeignKey('Trip')
    activity = models.ForeignKey(Activities)

    def __unicode__(self):
        return self.campsite

class Trip(models.Model):
    date = models.DateField()
    description = models.CharField(max_length=100)
    title = models.CharField(max_length=100)
    blog = models.TextField()

    def __unicode__(self):
        return self.title

class ActivityCon(models.Model):
    trip = models.ForeignKey(Trip)
    rating = models.IntegerField()
    overall_review = models.TextField()
    activity = models.ForeignKey(Activities)

这是完整的 Traceback:

    Environment:


Request Method: POST
Request URL: http://localhost:8000/admin/content/campcon/add/

Django Version: 1.5
Python Version: 2.7.3
Installed Applications:
('django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.sites',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'campsites',
 'auth',
 'trips',
 'content',
 'activities',
 'django.contrib.admin')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware')


Traceback:
File "/usr/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  116.                         response = callback(request, *callback_args, **callback_kwargs)
File "/usr/lib/python2.7/site-packages/django/contrib/admin/options.py" in wrapper
  367.                 return self.admin_site.admin_view(view)(*args, **kwargs)
File "/usr/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapped_view
  91.                     response = view_func(request, *args, **kwargs)
File "/usr/lib/python2.7/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
  89.         response = view_func(request, *args, **kwargs)
File "/usr/lib/python2.7/site-packages/django/contrib/admin/sites.py" in inner
  202.             return view(request, *args, **kwargs)
File "/usr/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapper
  25.             return bound_func(*args, **kwargs)
File "/usr/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapped_view
  91.                     response = view_func(request, *args, **kwargs)
File "/usr/lib/python2.7/site-packages/django/utils/decorators.py" in bound_func
  21.                 return func(self, *args2, **kwargs2)
File "/usr/lib/python2.7/site-packages/django/db/transaction.py" in inner
  208.                 return func(*args, **kwargs)
File "/usr/lib/python2.7/site-packages/django/contrib/admin/options.py" in add_view
  958.                 self.log_addition(request, new_object)
File "/usr/lib/python2.7/site-packages/django/contrib/admin/options.py" in log_addition
  525.             action_flag     = ADDITION
File "/usr/lib/python2.7/site-packages/django/contrib/admin/models.py" in log_action
  18.         e = self.model(None, None, user_id, content_type_id, smart_text(object_id), object_repr[:200], action_flag, change_message)

Exception Type: TypeError at /admin/content/campcon/add/
Exception Value: 'CampSite' object has no attribute '__getitem__'

【问题讨论】:

【参考方案1】:

您的问题是您的 __unicode__ 函数在需要返回 unicode 字符串时返回模型对象。

您可以通过将 unicode() 函数添加到您的 __unicode__ 方法来实现此目的:

class CampCon(models.Model):
    campsite = models.ForeignKey(CampSite)
    trip = models.ForeignKey('Trip')
    Date = models.DateField()
    user = models.ForeignKey(User)
    overall_review = models.TextField()
    facilities_review = models.IntegerField()
    things_to_do = models.IntegerField()
    privacy = models.IntegerField()
    beauty = models.IntegerField()
    overall_rating = models.IntegerField()

    def __unicode__(self):
        return unicode(self.campsite)

class ImageDB(models.Model):
    campsite = models.ForeignKey(CampSite)
    user = models.ForeignKey(User)
    description = models.CharField(max_length=200)
    image = models.ImageField(upload_to='/home/bobby/Pictures/CampThat')
    date_uploaded = models.DateField()
    date_taken = models.DateField()
    trip = models.ForeignKey('Trip')
    activity = models.ForeignKey(Activities)

    def __unicode__(self):
        return unicode(self.campsite)

这将调用CampSite.__unicode__,这将返回campsite.name

【讨论】:

谢谢!你刚刚救了我。【参考方案2】:

改用这个方法:

   def __unicode__(self):
        return unicode(self.campsite)

【讨论】:

【参考方案3】:

如果您这样做,也会发生这种情况:

event_name = CharField(max_length = 250)

而不是这样:(正确的方式)

event_name = models.CharField(max_length = 250)

可能对某人有帮助

【讨论】:

【参考方案4】:

由于这是 Google 上的第一次点击:我在执行以下操作时遇到了类似的错误 ('ItemGroup' object has no attribute '__getitem__'):

class ItemGroup(models.Model):
    groupname = models.CharField(max_length=128)

    def __unicode__(self):
        return "%s" % self.groupname

class Item(models.Model):
    name = models.CharField(max_length=128)
    group = models.ForeignKey(MedGroup, verbose_name="Groep")

    def __unicode__(self):
        return "%s (%s)" % (self.name, self.group[:10])

最后一行是错误的。

已通过将该行替换为 return "%s (%s)" % (self.name, self.group.groupname[:10]) 来解决此问题

【讨论】:

以上是关于TypeError 'x' 对象没有属性 '__getitem__'的主要内容,如果未能解决你的问题,请参考以下文章

TypeError:“NoneType”对象没有属性“__getitem__”

我得到一个“TypeError:'int'对象没有属性'_getitem',我不知道为啥

TypeError:“__ensemble__”对象不可调用

'numpy.ndarray'对象没有属性'index'

Python - TypeError: '...' 类型的对象没有 len()

TypeError:无法读取未定义的属性(读取“匹配”):