【问题标题】:Django OneToOne field in model's string representation模型字符串表示中的 Django OneToOne 字段
【发布时间】:2013-04-13 06:10:05
【问题描述】:

我尝试扩展 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) 吗?

【问题讨论】:

    标签: django django-models


    【解决方案1】:

    您的模型实际上是在 __unicode__ 方法中返回一个模型对象,而不是它应该返回 unicode 字符串,您可以这样做:

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

    这将调用User.__unicode__,它会返回user.username。感谢Nathan Villaescusa 他的answer

    您也可以在__unicode__方法中直接返回用户的用户名:

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

    【讨论】:

    • 谢谢你的作品。我认为用户字段会将调用转发到用户模型的 '__unicode__()' - 经验教训。
    猜你喜欢
    • 2016-06-10
    • 2015-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-09
    相关资源
    最近更新 更多