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
geeksforgeeks having an app named
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
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.
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 GeeksModel 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
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.geeks_field in above function will return the string stored in geeks_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.