【问题标题】:Trouble with _unicode() method in djangodjango 中的 _unicode() 方法有问题
【发布时间】:2012-05-10 18:25:28
【问题描述】:

我正在向我的模型添加一个 unicode() 方法,但是在交互中显示所有对象时它不起作用。

import datetime
from django.db import models
from django.utils import timezone

class Poll(models.Model):
    question = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')
    def _unicode_(self):
        return self.question
    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)

class Choice(models.Model):
    poll = models.ForeignKey(Poll)
    choice = models.CharField(max_length=200)
    votes = models.IntegerField()
    def _unicode_(self):
        return self.choice
# Create your models here.

(InteractiveConsole

>>> from polls.models import Poll, Choice
>>> Poll.objects.all()
[<Poll: Poll object>]

【问题讨论】:

    标签: django


    【解决方案1】:

    它们需要命名为__unicode__(两边各有两个下划线)。这是 Python 保留方法的一个尴尬细节,通过查看它们并不会立即明显。

    【讨论】:

      【解决方案2】:

      django 文档向您展示了如何在模型中指定 unicode 方法:
      https://docs.djangoproject.com/en/dev/ref/models/instances/?from=olddocs#other-model-instance-methods

      class Person(models.Model):
          first_name = models.CharField(max_length=50)
          last_name = models.CharField(max_length=50)
      
          def __unicode__(self):
              return u'%s %s' % (self.first_name, self.last_name)
      

      注意:这些是双下划线,在您的示例中,您只使用单下划线。

      它是一个标准的python特殊类方法,as listed here

      【讨论】:

      • 我更改了代码,但仍然无法正常工作。顺便说一句,根据这里的指南:link 我之前的代码是正确的。
      • @fpena06:在你提供的那个链接上没有写_unicode。另外,我认为你错过了它是双下划线。您提供的链接还显示双下划线__unicode__
      猜你喜欢
      • 1970-01-01
      • 2011-06-12
      • 1970-01-01
      • 2015-08-28
      • 2011-08-28
      • 1970-01-01
      • 2019-09-07
      • 1970-01-01
      • 2017-10-08
      相关资源
      最近更新 更多