Open In App

Customize Object Names with __str__ Method

Last Updated : 21 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

When you create instances of a Django model, by default, they appear in the Django admin interface and elsewhere as "ModelName object (1)" (or a similar format). This can make it hard to identify records, especially when you have many objects.

Why Customize Object Display Names?

By default, Django doesn’t know how to represent your objects as readable strings, so it uses a generic placeholder. Customizing the display name helps you and your users quickly identify objects in the admin panel and anywhere else the object is displayed as a string.

This article explains how to customize the display name of your Django model instances by overriding the __str__ method in your model class. This makes the admin interface and other representations much more meaningful and easier to understand.

Example: Default Behavior

Consider a project named geeksforgeeks having an app named geeks

Refer to the following Articles to check how to create Django App and Project:

Enter the following code into models.py file of geeks app.

Python
from django.db import models
from django.db.models import Model
# Create your models here.

class GeeksModel(Model):
    geeks_field = models.CharField(max_length = 200)

After running migrations and creating an instance with "GfG is Best" as the geeks_field value, the object will appear as GeeksModel object(1) in the admin interface, which isn’t very descriptive.:

display name django models

How to Customize the Display Name Using __str__

To change this, add a __str__ method to your model. This method should return a string that represents the object in a human-readable way.

Here’s how to modify the GeeksModel:

Python
from django.db import models

class GeeksModel(models.Model):
    geeks_field = models.CharField(max_length=200)
    
    def __str__(self):
        return self.geeks_field  # Returns the value of geeks_field as the display name

Now, when you create an object with geeks_field="GfG is Best", the admin interface will display "GfG is Best"

instead of the generic "GeeksModel object (1)":

django-object-name-display

Key Points to Remember

  • The __str__ method must return a string.
  • It’s best to return a value that uniquely and clearly identifies the object.
  • You can customize the return string as needed, for example, combining multiple fields:

Next Article
Practice Tags :

Similar Reads