In this Django Tutorial we are going to learn about Django Shell, also we are going to learn how you can do CRUD operations on your created model using Django Shell, so Django Shell is like Python Interpreter and you can do all CRUD operations using django shell on your database tables.
So now we want to open our Django Shell, you can use this command for opening, make sure that you have changed directory to your django project.
1 |
python manage.py shell |
OK now we want to do some CRUD operations on our Question model, and we want to make queries on our model , in the first we want to insert some data to our Question table. Once you’ve created your data models, Django automatically gives you a database-abstraction API that lets you create, retrieve, update and delete objects.
So let’s insert data to our Question model, in this code first we need to import our Question model with timezone from django, after you need to instantiate your model, because to represent database-table data in Python objects, Django uses an intuitive system: A model class represents a database table, and an instance of that class represents a particular record in the database table. to create an object, instantiate it using keyword arguments to the model class, then call save() method to save it to the database. the save() method perform INSERT SQL statement behind the scenes
1 2 3 4 |
>>> from polls.models import Question >>> from django.utils import timezone >>> q = Question(text='What is python inheritance ? ', pub_date = timezone.now()) >>> q.save() |
Now if you check your SQLite database in SQLite Studio, you have the data.
OK now let’s update our data, to save changes to an object that’s already in the database, use save() method.
1 2 |
>>> q.text ="This is updated" >>> q.save() |
This performs an UPDATE
SQL statement behind the scenes. Django doesn’t hit the database until you explicitly call save().
You can see that our second record is updated.
Also you can delete a record from your database tables using delete() method, this will perform a delete operations on your records.
1 |
>>> q.delete() |
Now let’s retrieve our data, there are different ways that you can retrieve the data, the first way is that you can simply use all() method, and using this method you can get all the data from the database table.
1 |
>>> data = Question.objects.all() |
Also you can use filter() for getting filtered data.
1 |
>>> filter_q = Question.objects.filter(pub_date__year=2020) |
1 |
>>> filter_q = Question.objects.filter(text__startswith='what') |
If you want to retrieve just one record than you can use get() method.
1 |
one_entry = Question.objects.get(pk=1) |