2012-09-07 22 views
2

我正在關注使用Django/Python創建論壇的lightbird教程。以下是創建Thread模型的代碼。這是什麼「return unicode(self.creator)+」 - 「+ self.title」在Django中做什麼?

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 

我明白這一點,但不是在上述模型中的代碼。有人可以請我解釋一下。謝謝!

回答

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")) 

將調用用戶類的__str__(或者__unicode__)函數創建者

然後將其添加破折號和標題

\n是端線

strftime將時間戳轉換爲英語「MonthAbbrv。 Day,24Hr:Minutes「