1 # -*- coding: utf-8 -*-
3 2. Adding __str__() or __unicode__() to models
5 Although it's not a strict requirement, each model should have a
6 ``_str__()`` or ``__unicode__()`` method to return a "human-readable"
7 representation of the object. Do this not only for your own sanity when dealing
8 with the interactive prompt, but also because objects' representations are used
9 throughout Django's automatically-generated admin.
11 Normally, you should write ``__unicode__()`` method, since this will work for
12 all field types (and Django will automatically provide an appropriate
13 ``__str__()`` method). However, you can write a ``__str__()`` method directly,
14 if you prefer. You must be careful to encode the results correctly, though.
17 from django
.db
import models
19 class Article(models
.Model
):
20 headline
= models
.CharField(max_length
=100)
21 pub_date
= models
.DateTimeField()
24 # Caution: this is only safe if you are certain that headline will be
28 class InternationalArticle(models
.Model
):
29 headline
= models
.CharField(max_length
=100)
30 pub_date
= models
.DateTimeField()
32 def __unicode__(self
):
35 __test__
= {'API_TESTS':ur
"""
37 >>> from datetime import datetime
38 >>> a = Article(headline='Area man programs in Python', pub_date=datetime(2005, 7, 28))
42 'Area man programs in Python'
45 <Article: Area man programs in Python>
47 >>> a1 = InternationalArticle(headline=u'Girl wins €12.500 in lottery', pub_date=datetime(2005, 7, 28))
49 # The default str() output will be the UTF-8 encoded output of __unicode__().
51 'Girl wins \xe2\x82\xac12.500 in lottery'