In the previous topic, you had seen how to create an object for a model, and after creating an object you got something like this :
<Person: Person object (1)>
The name <Person: Person object (1)>
is the name give by django as a default value. This is not in human readable format. You can convert this into human readable format by defining a __str__
method in your model. Converting into human readable format would be helpful when working with the django admin interface or when debugging the code.
The __str__
method can be defined as follows for the Person model:
def __str__(self):
return f"{self.first_name} {self.last_name}"
Here the first name and last name of the person is concatenated and returned by the function.
If you try to create an object for the model now, it would give an output in this format.
Person.objects.create(first_name='Programming', last_name='Master', birth_date='1992-10-15')
Here you will get an output like this :
<Person: Programming Master>
Which is the same as specified in the __str__
function. Note : After editing the models.py
file, you will need to restart the shell.
Similarly, if you try to view all the objects, the first object also will come in this format.
Person.objects.all()