python - In Django, why do I need __unicode__? -


i'm starting learn django , i'm starting out django book. came across concept , have hard time understanding logic..

the book says "django uses unicode objects throughout framework. model objects retrieved unicode objects, views interact unicode data, , templates rendered unicode. generally, won’t have worry making sure encodings right; things should work."

then why need "def unicode()" print in unicode? shouldn't work plain vanilla print()?

have tried printing model instance doesn't have __unicode__ method? don't useful. that's __unicode__ comes play. define how model instances displayed whenever try use them in unicode context.

try experiment. create simple model. print out:

class mymodel(models.model):     name = models.charfield(max_length=20)  >>> obj = mymodel("foo") >>> print obj 

see get. add __unicode__() method.

class mymodel(models.model):     name = models.charfield(max_length=20)      def __unicode__(self):         return self.name 

run again:

>>> obj = mymodel("foo") >>> print obj 

Comments

Popular posts from this blog

c# - How Configure Devart dotConnect for SQLite Code First? -

c++ - Clear the memory after returning a vector in a function -

erlang - Saving a digraph to mnesia is hindered because of its side-effects -