Working With Models
We have defined a model and applied the migrations. It remains for us to see how to use the model to add and return courses from the database. We'll do some testing using Django's interactive console, which is a regular Python shell, but with access to the modules of our application. To start the Django shell, run:
python manage.py shell
Since we want to work with the Course
model defined in myapp/models.py
, import that class:
>>> from myapp.models import Course
Inserting data
Now, if you want to create a new course and add it to the database (which would internally execute an SQL INSERT
statement), you can do:
>>> python_course = Course(name="Python", enrolled_students=10)
>>> python_course.save()
The procedure is always the same: create an instance of the model, giving as arguments the values for each field, and then call the save()
function that saves the object in the database.
Using the database browser, let's check that the course has actually been created:
As you can see, in addition to the name
and enrolled_students
fields that we defined in the model, Django automatically adds the id
field, a unique number that serves as the identifier of a row in the table.
Now that you have a first course created, you can access its fields as attributes of an object:
>>> python_course.id
1
>>> python_course.name
'Python'
>>> python_course.enrolled_students
10
If you change the value of a field, you must call save()
again so that the changes are reflected in the database:
>>> python_course.name = "Advanced Python"
>>> python_course.save()
Let's look at another example:
>>> java_course = Course.objects.create(name="Java", enrolled_students=12)
>>> java_course.id
2
>>> java_course.name
'Java'
>>> java_course.enrolled_students
12
We just used an alternative syntax: the Course.objects.create()
function operates in a similar way, except that it automatically calls the save()
function of the created course and returns the saved object.
Another example:
>>> php_course = Course.objects.create(name="PHP", enrolled_students=8)
>>> php_course.id
3
>>> php_course.name
'PHP'
>>> php_course.enrolled_students
8
Retrieving data
To retrieve values from the database (the equivalent of a SELECT
statement in SQL), use:
>>> courses = Course.objects.all()
The all()
function returns all objects stored in the database. The data type of the return value is a special collection type defined by Django called QuerySet
.
>>> type(courses)
<class 'django.db.models.query.QuerySet'>
QuerySets
are similar to Python lists, that is, you can iterate over them using “for” loops and use the square bracket syntax to access their elements:
>>> courses[0].name
'Advanced Python'
>>> courses[0].enrolled_students
10
>>> courses[1].name
'Java'
>>> courses[1].id
2
>>> for course in courses:
... print(course.name)
...
Advanced Python
Java
PHP
You can also find the SQL query (when working with a relational database) that Django executed to create the QuerySet
:
>>> str(courses.query)
'SELECT "myapp_course"."id", "myapp_course"."name", "myapp_course"."enrolled_students" FROM "myapp_course"'
To fetch only one object from the database, it is optimal to use the Course.objects.get()
function, which usually works by passing as an argument the id of the object you want to fetch. However, if the id is not known, it can also be searched from the value of any other field, as long as it is unique across the table.
>>> java_course = Course.objects.get(id=2)
>>> java_course.name
'Java'
>>> php_course = Course.objects.get(name="PHP")
>>> php_course.id
3
>>> php_course.enrolled_students
8
If no object is found that matches the value given as argument, the Course.DoesNotExist
exception is raised. Django automagically defines an exception called DoesNotExist
inside your models that is used in these cases:
Traceback (most recent call last):
...
myapp.models.Course.DoesNotExist: Course matching query does not exist.
The return value of Course.objects.get()
is always an instance of Course
, as you can see:
>>> type(java_course)
<class 'myapp.models.Course'>
>>> type(php_course)
<class 'myapp.models.Course'>
Summary
In summary, the main operations to interact with the database so far are the following:
MyModel.objects.create(...)
to insert.MyModel.objects.all()
to return all objects.MyModel.objects.get(...)
to retrieve a single object by id or other unique field.
We'll see more about this in the next section.
To exit the Django interactive console, run:
>>> quit()