views:

75

answers:

4

Class mytable(models.Model): abc = ... xyz = ... def unicode(self):

Why is the def ___unicode___ necessary?

+1  A: 

so the admin can display its breadcrumbs, and you are able to put {{ myobject }} into a template to show the __unicode__ of your object.

mawimawi
In the template, why do I need to show the __unicode__ of the object?
TIMEX
for example: `<a href="{{ object.get_absolute_url }}">{{ object }}</a>`And it's "unicode" instead of "str" because django uses unicode everywhere.
mawimawi
+2  A: 

__unicode__ is a Python "magic method" that determines how your object looks when you want to display that object as a unicode string. It's not Django-specific or anything, but any time you either call str() or unicode() or use string interpolation and pass that object in, it will call that method to determine what unicode string is returned.

For objects displayed in templates, this method will be called to determine what is displayed in the template because this is the method that Python uses to determine what an object looks like as a character string.

Daniel DiPaolo
+4  A: 

These resources do a far better job at explaining that I can:

Django Docs
Python Docs
__str__ versus __unicode__

In short, you need to define __unicode__ so Django can print some readable representation when you call an object. __unicode__ is also the 'new' preferred way to return your character string.

Nick Presta
A: 

In my experience, there is one very important reason why to define the __unicode__ method: the Django shell.

Playing with the console is usually a very powerful tool while developing a Django application, because it allows inspection of your (and others) classes, as well as quick prototype ideas and solutions.
And, working in the shell, every time you do a print a where a is a model instance, you will thank a lot having a __unicode__ method that allows to easily recognize what object are you working with.

Roberto Liffredo