2013-05-17 116 views
8

我有兩個模型是這樣的:對象有沒有屬性「__getitem__」

class School(models.Model): 
    name = models.CharField(max_length = 50) 

    def __unicode__(self): 
     return self.name 

class Education(models.Model): 
    user_profile = models.ForeignKey(UserProfile, related_name='Education') 
    school = models.OneToOneField(School) 

    def __unicode__(self): 
     return self.school 

當我想補充一個教育和Django管理員USERPROFILE這個錯誤eccour:

Traceback: 
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response 
    115.       response = callback(request, *callback_args, **callback_kwargs) 
File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/options.py" in wrapper 
    372.     return self.admin_site.admin_view(view)(*args, **kwargs) 
File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in _wrapped_view 
    91.      response = view_func(request, *args, **kwargs) 
File "/usr/local/lib/python2.7/dist-packages/django/views/decorators/cache.py" in _wrapped_view_func 
    89.   response = view_func(request, *args, **kwargs) 
File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/sites.py" in inner 
    202.    return view(request, *args, **kwargs) 
File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in _wrapper 
    25.    return bound_func(*args, **kwargs) 
File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in _wrapped_view 
    91.      response = view_func(request, *args, **kwargs) 
File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in bound_func 
    21.     return func(self, *args2, **kwargs2) 
File "/usr/local/lib/python2.7/dist-packages/django/db/transaction.py" in inner 
    223.     return func(*args, **kwargs) 
File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/options.py" in add_view 
    1009.     self.log_addition(request, new_object) 
File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/options.py" in log_addition 
    530.    action_flag  = ADDITION 
File "/usr/local/lib/python2.7/dist-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/social/education/add/ 
Exception Value: 'School' object has no attribute '__getitem__' 

我怎麼能修復這個錯誤?

回答

12

要解決此問題,您需要__unicode__返回str(不是對象)。

def __unicode__(self): 
    return unicode(self.school) 
+1

+1,或者直接返回'self.school.name',這畢竟可能更合適。另外,您可能希望避免'related_name ='Education'',因爲它已經是類的名稱 –

+3

更好的是返回'unicode(self.school)',因爲它預期會返回unicode。 – Rohan

+0

o ...謝謝!:d –

相關問題