Open In App

Change Object Display Name using __str__ function – Django Models | Python

Improve
Improve
Like Article
Like
Save
Share
Report

How to Change Display Name of an Object in Django admin interface? Whenever an instance of model is created in Django, it displays the object as ModelName Object(1). This article will explore how to make changes to your Django model using def __str__(self) to change the display name in the model.

Object Display Name in Django Models

Consider a project named geeksforgeeks having an app named geeks.

Refer to the following articles to check how to create a project and an app in Django.

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




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 makemigrations and migrate on Django and rendering above model, let us try to create an instance using string “GfG is Best“.
django-object-name-display
Now it will display the same object created as GeeksModel object(1) in the admin interface.
display name django models

How to change display name of Model Instances in Django admin interface?

To change the display name we will use def __str__() function in a model. str function in a django model returns a string that is exactly rendered as the display name of instances for that model.
For example, if we change above models.py to




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)
     
    def __str__(self):
         return "something"


This will display the objects as something always in the admin interface.
django-display-name-something

Most of the time we name the display name which one could understand using self object. For example return self.geeks_field in above function will return the string stored in geeks_field of that object and it will be displayed in admin interface.
django-display-name-gfg-is-best.

Note that str function always returns a string and one can modify that according to one’s convenience.

Also Check –



Last Updated : 13 Feb, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads