django models.py中的__unicode__ __str__的作用

在django的models.py 构造表结构后,后面会经常跟一串__unicode__(python2)  __str__(python3)函数。对于这个函数的作用,在网上参考了大牛们的注释,这个解释的比较清楚了https://segmentfault.com/q/1010000006121303

models.py

from __future__ import unicode_literals

from django.db import models

# Create your models here.
class Person(models.Model):
    name=models.CharField(max_length=30)
    age=models.IntegerField()

    def __unicode__(self):
        return self.name

简单翻译下就是,当不存在这个函数的时候,打印的结果会不美观,为了改善显示效果,就用到了__unicode__这个方法了。具体了可以参考上面的链接信息。

猜你喜欢

转载自blog.csdn.net/zhouxuan623/article/details/84838841
今日推荐