• 关于django模型里面的__str__和__unicode


    简而言之,就是__str__和__unicode__都是为了再管理站点中加载这个表时想显示什么属性,当然一般都是显示一个name,大体来讲是通用的。下面是抄的csdn上面的一篇文章。

    str()是Python的一个“魔幻”方法,这个方法定义了当object调用str()时应该返回的值。Django在许多地方使用str(obj)(或者相关方法,unicode(obj)——见下文),比如说在Django管理站点加载一个对象时显示它的值或者作为对象的显示值插入模板中。因此,我们应该总是返回一个友好的,用户可读的字符串作为对象的str。尽管这不是必须的,但还是建议这么做。例如:

    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()方法是在一个对象上调用unicode()时被调用的。因为Django的数据库后端会返回Unicode字符串给model属性,所以我们通常会给自己的model写一个unicode()方法。前面的例子也可以更简单地写成:

    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)

    如果定义了unicode()方法但是没有定义str()方法,Django会自动提供一个str()方法调用unicode()方法,然后把结果转换为UTF-8编码的字符串对象。在实际开发中,建议:只定义unicode()方法,需要的话让Django来处理字符串对象的转换。

  • 相关阅读:
    男子胃脘胀痛案(知老)
    转 Django中的Form
    转 Alert.log shows No Standby Redo Logfiles Of Size 153600 Blocks Available
    转发 django 初探
    转 Logs are not shipped to the physical standby database
    python 之django (一) Windows环境下Django 1.6.11开发环境搭建(简易版)
    oracle db 产品路线图
    转 python中%s与%d
    转 python 的常用函数replace, split(),enumerate() 函数
    转 [Error]EOL while scanning string literal
  • 原文地址:https://www.cnblogs.com/painberg/p/8514860.html
Copyright © 2020-2023  润新知