2

我正在关注关于使用 Django/Python 创建论坛的 lightbird 教程。这是创建Thread模型的代码。

class Thread(models.Model):
    title = models.CharField(max_length=100)
    created = models.DateTimeField(auto_now_add=True)
    creator = models.ForeignKey(User, blank=True, null=True)
    modified = models.DateTimeField(auto_now=True)
    forum = models.ForeignKey(Forum)

    def __unicode__(self):
        return unicode(self.creator) + " - " + self.title

还有一个Post模型:

class Post(models.Model):
    title = models.CharField(max_length=60)
    created = models.DateTimeField(auto_now_add=True)
    creator = models.ForeignKey(User, blank=True, null=True)
    thread = models.ForeignKey(Thread)
    body = models.TextField(max_length=10000)

    def __unicode__(self):
        return u"%s - %s - %s" % (self.creator, self.thread, self.title)

    def short(self):
        return u"%s - %s\n%s" % (self.creator, self.title, self.created.strftime("%b %d, %I:%M %p"))
    short.allow_tags = True

我很难理解unicode函数后的代码!在以非常简单的形式创建模型时,我一直在使用unicode ,例如:

class Post(models.Model):
    title = models.CharField(max_length=100)

    def __unicode__(self):
        return self.title

我理解这一点,但不理解上述模型中的代码。有人可以向我解释一下吗。谢谢!

4

1 回答 1

5
 unicode(self.creator) +\ #will call the __unicode__ method of the User class
 ' - ' +\ # will add a dash
 self.title #will add the title which is a string

然后是第二个

  "%s"%some_var #will convert some_var to a string (call __str__ usually...may fall back on __unicode__ or something)

所以

return u"%s - %s\n%s" % (self.creator, self.title, self.created.strftime("%b %d, %I:%M %p"))

将为创建者调用 User 类上的__str__(或可能)函数__unicode__

然后它添加一个破折号和标题

\n是结束线

并将strftime时间戳转换为英文“MonthAbbrv. Day, 24Hr:Minutes”

于 2012-09-07T04:28:07.527 回答