need some explanation

62 views
Skip to first unread message

Hussain Nagri

unread,
Dec 4, 2013, 2:20:03 AM12/4/13
to django...@googlegroups.com
Hello,
I am new to Django and trying to learn myself.
My question is that when we create models in model.py then after each class we define a '__unicode__'. Is it necessary that we define this method ? It gets called every time I try to fetch any data from that model. what if I don’t want it to run every time I try to fetch data ?

any help will be appreciated.

Thank you

Tom Evans

unread,
Dec 4, 2013, 8:27:39 AM12/4/13
to django...@googlegroups.com
__unicode__ is a generic python method that is used when you try to
convert an object to a unicode string, either by formatting it in to a
buffer or printing it or anything that evaluates it as a (unicode)
string. It is not run when you "fetch data", but only when you convert
an instance to a unicode string.

If you do not provide one for your class, then the one from the base
django Model class will be used, which prints out something like
"<FooType: FooType object>" (assuming the class is called "FooType").

Cheers

Tom

Scot Hacker

unread,
Dec 5, 2013, 11:43:39 AM12/5/13
to django...@googlegroups.com, teva...@googlemail.com
On Wednesday, December 4, 2013 5:27:39 AM UTC-8, Tom Evans wrote:
On Wed, Dec 4, 2013 at 7:20 AM, Hussain Nagri <nagr...@gmail.com> wrote:
> Hello,
> I am new to Django and trying to learn myself.
> My question is that when we create models in model.py then after each class
> we define a '__unicode__'. Is it necessary that we define this method ? It
> gets called every time I try to fetch any data from that model. what if I
> don’t want it to run every time I try to fetch data ?


 As Tom says, your model instances have to be represented on-screen *somehow*, so Python is going to run *something* to calculate what that representation should be. You should define it so you get the representation you want rather than going with the defaults - you're not going to save measurably on performance by skipping the _unicode_ definition.

./s

Reply all
Reply to author
Forward
0 new messages