1

我尝试扩展 django 的身份验证模型,并通过 OneToOneField 向用户添加一些特殊字段。

from django.db import models
from django.contrib.auth.models import User


class GastroCustomer(models.Model):
    user = models.OneToOneField(User)
    barcode = models.IntegerField()
    balance = models.IntegerField()

    def __unicode__(self):
        return self.user

这在管理模块之外工作正常。但是,如果我现在开始GastroCustomer通过管理界面添加一个新的,我会收到: 'User' object has no attribute '__getitem__'

如果我换成__unicode__(self)简单的东西,例如

def __unicode__(self):
    return "foo"

不会发生此错误。有没有办法确定这个用户字段何时处于某种无效状态并更改这种情况下的字符串表示?有人能想象为什么__unicode__(self)在记录“正确”之前被调用吗?

4

1 回答 1

2

Your model is actually returning a model object in __unicode__ method instead it should return unicode string, you can do this:

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

This will call User.__unicode__ which will return user.username. Thanks to Nathan Villaescusa on his answer.

Alternatively you can directly return the username of user in __unicode__ method:

def __unicode__(self):
    return self.user.username
于 2013-04-19T19:03:09.570 回答