Friday, December 27, 2024
Google search engine
HomeLanguagesChange Object Display Name using __str__ function – Django Models | Python

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 neveropen having an app named Lazyroar.

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




from django.db import models
from django.db.models import Model
# Create your models here.
  
class GeeksModel(Model):
    Lazyroar_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):
    Lazyroar_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.Lazyroar_field in above function will return the string stored in Lazyroar_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 –

RELATED ARTICLES

Most Popular

Recent Comments