Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of unicode in Django

Tags:

python

django

Why is a unicode function required in models.py?

i.e,

def __unicode__(self)
    return sumid;
like image 663
Hulk Avatar asked Nov 30 '09 06:11

Hulk


2 Answers

It's not. If you define a __unicode__() method, Django will call it when it needs to render an object in a context where a string representation is needed (e.g. in the model's admin pages).

The documentation says:

The __unicode__() method is called whenever you call unicode() on an object. Since Django's database backends will return Unicode strings in your model's attributes, you would normally want to write a __unicode__() method for your model.

like image 54
Dominic Rodger Avatar answered Sep 18 '22 18:09

Dominic Rodger


I'm a bit new to Django, but I think I can help you.

First, it isn't exactly required, but it's a really good idea. The field is used to create representations of your objects in the Django admin (otherwise they all have the same name :-P) and when you print out an object to your terminal window to see what's going on (otherwise you get a generic mostly useless message).

Second, from what you wrote, it looks like you're new to Python. I recommend reading some Python tutorials on class syntax. Also, semicolons aren't necessary in this language. The correct syntax for creating the unicode method is:

class Foo(models.Model):
    # Model fields go here

    def __unicode__(self):
        return u"%i" % self.sumid

The __unicode__ method has double underscores because it is a special function, namely when the builtin function unicode( obj ) is called on it, it returns a unicode string representation of that object (sort of like java's ToString).

I hope this helps :-)

like image 42
SapphireSun Avatar answered Sep 18 '22 18:09

SapphireSun