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

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 w3wiki having an app named Beginner.

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 Beginner app.




from django.db import models
from django.db.models import Model
# Create your models here.
  
class BeginnerModel(Model):
    Beginner_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β€œ.

Now it will display the same object created as BeginnerModel object(1) in the admin interface.

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 BeginnerModel(Model):
    Beginner_field = models.CharField(max_length = 200)
     
    def __str__(self):
         return "something"


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

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

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

Also Check –