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.
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值