Django Tutorial
About Lesson

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.



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




Now if you check your SQLite database in SQLite Studio, you have the data.

Django Tutorial - Django Shell
Django Tutorial – Django Shell




OK now let’s update our data, to save changes to an object that’s already in the database, use save() method.

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.

Django Shell
Django Shell




Also you can delete a record from your database tables using delete() method, this will perform a delete operations on your records.




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.



Also you can use filter() for getting filtered data.




If you want to retrieve just one record than you can use get() method.