24
You created a Blog model. Once you migrate this, Django will create a table with "name" and "tagline" columns in your database.
If you want to interact with the database with the model, for example create an instance of the model and save it or retrieve the model from db,
def __str__(self):
return self.name
will come handy. Open the python interactive shell in your project’s root folder via:
python manage.py shell
Then
from projectName.models import Blog
Blog.objects.all() # will get you all the objects in "Blog" table
Also, when you look at the models in your admin panel, you will see your objects listed, with the name property.
The problem is, the return will look like this if you did not add that function:
<QuerySet [<Blog:>,<Blog:>,<Blog:>....]
So you will not know what those objects are. A better way to recognize those objects is retrieving them by one of its properties which you set it as name. This way you will get the result as follow:
<QuerySet [<Blog:itsName>,<Blog:itsName>,<Blog:itsName>....]
If you want to test this out, run python manage.py shell
and run:
from projectName.models import Blog
# The below will create and save an instance.
# It is a single step. Copy-paste multiple times.
Blog.objects.create(name="first",tagline="anything")
Blog.objects.all() # check out the result
15
The __str__
method just tells Django what to print when it needs to print out an instance of the any model. It is also what lets your admin panel, go from this
Note: how objects are just plainly numbered
to this
Note: proper object names here
You could choose what to show in the admin panel, as per your choice. Be it a field value or a default value or something else.
- [Django]-Should I be adding the Django migration files in the .gitignore file?
- [Django]-How to use Faker from Factory_boy
- [Django]-Django py.test does not find settings module
8
This overrides the default name of the objects of this class, it’s something like Author:object
which isn’t very helpful.
overriding it gives a more human friendly name of the object like the Author.name
- [Django]-How about having a SingletonModel in Django?
- [Django]-How do I use CommaSeparatedIntegerField in django?
- [Django]-Load a Django template tag library for all views by default
4
def str(self): is a python method which is called when we use print/str to convert object into a string. It is predefined , however can be customised. Will see step by step.Suppose below is our code.
class topics():
def __init__(self,topics):
print "inside init"
self.topics=topics
my_top = topics("News")
print(my_top)
Output:
inside init
<__main__.topics instance at 0x0000000006483AC8>
So while printing we got reference to the object. Now consider below code.
class topics():
def __init__(self,topics):
print "inside init"
self.topics=topics
def __str__(self):
print "Inside __str__"
return "My topics is " + self.topics
my_top = topics("News")
print(my_top)
Output:
inside init
Inside __str__
My topics is News
So, here instead of object we are printing the object. As we can see we can customize the output as well. Now, whats the importance of it in a django models.py file?
When we use it in models.py file, go to admin interface, it creates object as “News”, otherwise entry will be shown as main.topics instance at 0x0000000006483AC8 which won’t look that much user friendly.
- [Django]-How to filter empty or NULL names in a QuerySet?
- [Django]-Pipfile.lock out of date
- [Django]-Necessity of explicit cursor.close()
2
The __str__
function is used add a string representation of a model’s object, so that is
to tell Python what to do when we convert a model instance into a string.
And if you dont mention it then it will take it by default the USERNAME_FIELD
for that purpose.
So in above example it will convert Blog
and Author
model’s object to their associated name
field and the objects of Post
model to their associated headline
field
- [Django]-How do Django models work?
- [Django]-Django Rest Framework: Disable field update after object is created
- [Django]-Django bulk_create function example
2
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.
- [Django]-Django: Adding "NULLS LAST" to query
- [Django]-Django – Where are the params stored on a PUT/DELETE request?
- [Django]-Django get a QuerySet from array of id's in specific order
1
For example, you define __str__() in Person
model as shown below:
# "models.py"
from django.db import models
class Person(models.Model):
first_name = models.CharField(max_length=20)
last_name = models.CharField(max_length=20)
def __str__(self): # Here
return self.first_name + " " + self.last_name
Then, you define Person
admin as shown below:
# "admin.py"
from django.contrib import admin
from .models import Person
@admin.register(Person)
class PersonAdmin(admin.ModelAdmin):
pass
Now, the full name is displayed in the message and list in "Change List" page:
And in "Change" page:
And in "Delete" page:
Next, if you don’t define __str__()
in Person
model as shown below:
# "models.py"
from django.db import models
class Person(models.Model):
first_name = models.CharField(max_length=20)
last_name = models.CharField(max_length=20)
# def __str__(self): # Here
# return self.first_name + " " + self.last_name
Now, the object name and id are displayed in the message and list in "Change List" page:
And in "Change" page:
And in "Delete" page:
- [Django]-How do I get multiple values from checkboxes in Django
- [Django]-Getting the SQL from a Django QuerySet
- [Django]-Getting a count of objects in a queryset in Django
0
When you want to return the objects in that class then you’ll see something such as <QuerySet [object(1)]>
. However no body wants to see something like this. they want actual name that human can understand what exactly is present in that table, so they use this function.
- [Django]-Django – makemigrations – No changes detected
- [Django]-How do you log server errors on django sites
- [Django]-Django Rest Framework and JSONField