python __str__(self) __unicode__(self)

__str__

Model.__str__()

__str__() is a Python "magic method" that defines what should be returned if you call str() on the object. Django uses str(obj) (or the related function, unicode(obj) -- see below) in a number of places, most notably as the value displayed to render an object in the Django admin site and as the value inserted into a template when it displays an object. Thus, you should always return a nice, human-readable string for the object's __str__. Although this isn't required, it's strongly encouraged (see the description of __unicode__, below, before putting __str__ methods everywhere).

For example:

class Person(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)


    def __str__(self):
        # Note use of django.utils.encoding.smart_str() here because
        # first_name and last_name will be unicode strings.
        return smart_str('%s %s' % (self.first_name, self.last_name))
__unicode__


Model.__unicode__()

The __unicode__() method is called whenever you call unicode() on an object. Since Django's database backends will return Unicode strings in your model's attributes, you would normally want to write a __unicode__() method for your model. The example in the previous section could be written more simply as:

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)

If you define a __unicode__() method on your model and not a __str__() method, Django will automatically provide you with a __str__() that calls __unicode__() and then converts the result correctly to a UTF-8 encoded string object. This is recommended development practice: define only __unicode__() and let Django take care of the conversion to string objects when required.

你可能感兴趣的:(python,django,String,object,attributes,methods)