I\'m reading and trying to understand django documentation so I have a logical question.
There is my models.py
file
from django.db import mo
Django has __str__
implementations everywhere to print a default string representation of its objects. Django's default __str__
methods are usually not very helpful. They would return something like Author object (1)
. But that's ok because you don't actually need to declare that method everywhere but only in the classes you need a good string representation. So, if you need a good string representation of Author but not Blog, you can extend the method in Author only:
class Author(models.Model):
name = models.CharField(max_length=100)
...
def __str__(self):
return f'{self.name}' # This always returns string even if self.name is None
class Post(models.Model):
author = models.ForeignKey(Author, on_delete=models.CASCADE)
text = models.CharField(max_length=100)
author = Author.objects.create(name='David')
print(author) # David
post = Post.objects.create(author=author, text='some text')
print(post) # Post object(1)
Now, beyond Django, __str__
methods are very useful in general in Python.
More info here.