Django Adding a string representation of a model


Example

To create a human-readable presentation of a model object you need to implement Model.__str__() method (or Model.__unicode__() on python2). This method will be called whenever you call str() on a instance of your model (including, for instance, when the model is used in a template). Here's an example:

  1. Create a book model.

    # your_app/models.py
    
    from django.db import models
    
    class Book(models.Model):
        name = models.CharField(max_length=50)
        author = models.CharField(max_length=50)
    
  2. Create an instance of the model, and save it in the database:

    >>> himu_book = Book(name='Himu Mama', author='Humayun Ahmed')
    >>> himu_book.save()
    
  3. Execute print() on the instance:

    >>> print(himu_book)
    <Book: Book object>
    

<Book: Book object>, the default output, is of no help to us. To fix this, let's add a __str__ method.

from django.utils.encoding import python_2_unicode_compatible

@python_2_unicode_compatible
class Book(models.Model):
    name = models.CharField(max_length=50)
    author = models.CharField(max_length=50)

    def __str__(self):
        return '{} by {}'.format(self.name, self.author)

Note the python_2_unicode_compatible decorator is needed only if you want your code to be compatible with python 2. This decorator copies the __str__ method to create a __unicode__ method. Import it from django.utils.encoding.

Now if we call the print function the book instance again:

>>> print(himu_book)
Himu Mama by Humayun Ahmed

Much better!

The string representation is also used when the model is used in a ModelForm for ForeignKeyField and ManyToManyField fields.