2017-09-10 17 views
-2
# __unicode__ on Python 2 

Django的新手在這裏,我試圖尋找上述此評論的意義,但無法找到關於它的信息。可有人Django文檔中解釋的`#__unicode__意義上的Python 2`

在Django文檔中,我在代碼的許多部分發現了這個註釋,這是否意味着這一節只有當我使用Django與Python 2或它意味着別的東西?

我的意思是這樣

def __str__(self):    # __unicode__ on Python 2 
      return "%s the place" % self.name 

功能。在本實施例中的代碼:

from django.db import models 

class Place(models.Model): 
    name = models.CharField(max_length=50) 
    address = models.CharField(max_length=80) 

    def __str__(self):    # __unicode__ on Python 2 
     return "%s the place" % self.name 

class Restaurant(models.Model): 
    place = models.OneToOneField(
     Place, 
     on_delete=models.CASCADE, 
     primary_key=True, 
    ) 
    serves_hot_dogs = models.BooleanField(default=False) 
    serves_pizza = models.BooleanField(default=False) 

    def __str__(self):    # __unicode__ on Python 2 
     return "%s the restaurant" % self.place.name 

class Waiter(models.Model): 
    restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE) 
    name = models.CharField(max_length=50) 

    def __str__(self):    # __unicode__ on Python 2 
     return "%s the waiter at %s" % (self.name, self.restaurant) 

回答

1

這意味着樣本代碼寫入在Python 3,而如果編寫一個Python 2應用程序,您應該在您的類定義中將__str__替換爲__unicode__

Python 2和Python 3在很多方面有所不同,特別是在如何處理Unicode和字符串方面。

+0

謝謝你的插圖Alex –

相關問題