TIMEX
TIMEX

Reputation: 272074

Why do you need this method inside a Django model?

class mytable(models.Model):
    abc = ...
    xyz = ...
    def __unicode__(self):

Why is the def __unicode__ necessary?

Upvotes: 0

Views: 1707

Answers (4)

rob
rob

Reputation: 37644

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.

Upvotes: 1

Nick Presta
Nick Presta

Reputation: 28695

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.

Upvotes: 5

Daniel DiPaolo
Daniel DiPaolo

Reputation: 56408

__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.

Upvotes: 2

mawimawi
mawimawi

Reputation: 4343

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

Upvotes: 1

Related Questions