[Model examples] Adding __str__() to models

0 views
Skip to first unread message

憨狗

unread,
Jun 26, 2006, 1:49:49 AM6/26/06
to djan...@googlegroups.com

Adding __str__() to models

虽然这不是强制要求,但是建议每个model应该实现一个__str__()方法,以返回一个
可读性很强的对象,这样无论是在交互使用使用django shell或者Django的自动化管理
后台的时候,都会受益匪浅。


Model 代码

from django.db import models

class Article(models.Model):
headline = models.CharField(maxlength=100)
pub_date = models.DateTimeField()

def __str__(self):
return self.headline


Sample API 用法

上面的model实现在: bare_bones/models.py里面

>>> from bare_bones.models import Article

# 新建一篇文章
>>> from datetime import datetime
>>> a = Article(headline='Area man programs in Python', pub_date=datetime(2005, 7, 28))
>>> a.save()

>>> str(a)
'Area man programs in Python'

>>> a
<Article: Area man programs in Python>

Reply all
Reply to author
Forward
0 new messages