Check out a free preview of the full Practical Guide to Python course
The "Databases" Lesson is part of the full, Practical Guide to Python course featured in this preview video. Here's what you'd learn in this lesson:
Nina explores the Django project and the code that communicates with the SQLite database. Whenever a field is added or removed from the models in Django, the makemigrations and migrate commands should be run to update the database. The Django "shell" command allows models to be worked with in the command line.
Transcript from the "Databases" Lesson
[00:00:00]
>> Let's talk about how Django interacts with databases. Let's Ctrl+C out of this for just a moment and open up this folder in VS Code, either with code. Or by going to VS Code and saying File, Open, and then opening this folder. And let's open a Python file by using the Quick Find Ctrl+P or Command P and opening models.py.
[00:00:29]
And this will start the the Python extension, make sure you click down here and ensure that the right virtual environment is selected for me it's ./bin/Python. And that will clear up any if you saw some squigglies before, under here, that's because Django was not installed in the virtual environment that VS code selected.
[00:00:54]
I'm not sure why it's not selecting the right thing at the moment or recognizing my virtual environments. Maybe it's a weird setting on my side because it is something that usually works quite well. I've opened up models.py. And models.py lives in the blog folder, but I recommend that you open that up via the Quick Find.
[00:01:21]
This is a custom model that I've defined in Django and it's got a few fields in it. It's got a title which is the character field with a maximum of 300. It's got a body which is a text field. It's got a slug which is a newspaper term but you might see used commonly in blogs.
[00:01:42]
A slug is a way of taking a title and then adding, removing any special characters, adding dashes or underscores. That some of that title can be in the URL for the blog post for SEO purposes. And then we also have a created at field which is a date time field and a string representation of our model.
[00:02:08]
Now this model maps to a database, a sequel lite database that we have on our systems and we don't need to know anything about sequel or databases in order to use databases with Django, which is just great. Once we create our application here at the blog app, we're going to want to make sure that when we open settings.py, which is the global settings for our Django application, and we scroll down to installed_Apps, we want make sure that we have blog.apps.BlogConfig in here.
[00:02:45]
That tells Django to register various applications. Now, the practical blog directory is the project. Level directory where all the project specific settings live for my, this project. The blog directory has app specific stuff in it for my blog. When you're working on small Django projects, having multiple apps doesn't matter, but let's say you are a company.
[00:03:18]
And practical blog is your project. Now you might have an app for a blog, you might have an app for an e-commerce site. You might have an app for a forum. And those are all going to have their own individual folders in Django, where you can define your models and views and routes and everything for that specific app in its own happy little namespace.
[00:03:48]
Now, I'm not going to talk about how to make migrations, but if you do want to complete the final exercise, I recommend that you go back to. This section, anytime you change your models, let's say you delete one of these or you add a new one, you need to tell Django to make instructions for the database, to match the new model, and then run those instructions.
[00:04:16]
Let's say if you delete a field here, Django needs to issue instructions to drop a column from a table in a database. In order to do that, you need to run a command called make migrations. You can optionally pass in the name of the app here. It's called blog.
[00:04:37]
And then you can run the migrate command and that will go ahead and update your database so that it matches your latest models. If you want to work with models, you can do that in the python. Shell. I'm going to open up my terminal here. And type in Python managed.py followed by the word shell, this is going to bring up a special Django shell that knows a lot about how our project is structured.
[00:05:13]
It's a little bit different than just a standard ruppel, now we can work with our models and objects that we defined in Django in the shell. For example, I can say from blog.models, import posts, and that is the model that I had defined up there. Now I can query that model by saying, sorry, post.objects.all is going to query all of the tables, all the rows in this table.
[00:05:50]
Currently, we don't have any. If I wanted to, I have an example for creating posts. From the command line here, so let me just copy and paste this first post here. I'm defining all of the fields providing values for all of the fields I defined up here. Title body and slug everything except for created because I'm using this auto add auto now add equals true.
[00:06:23]
That means when I create a row in this database, it's going to automatically add the created at timestamp. In order for me to save this into my database I need to run first post.save and now, when I rerun my query, My first post is in here. Let's go ahead and open a new tab in VS code and start our server again.
[00:06:58]
Python manage.py runserver. If you never exited your server in the first place and you try to run it again, you might get an error about the port being busy or occupied. Know that means that you're probably already running your server in a different tab. There is my first post reflected in the webpage.
[00:07:24]
We can interact with these models, just like objects in Python. There's a get method so I can pass in to get get me where the slug is equal to first post. And that will return the record I just created, if I say first post to I'm going to get an exception here, post does not exist.
[00:07:56]
There's no post matching your query makes sense. I can also use the dot filter method. Get will get you one result dot filter will get you a list. And you'll see that you got a query set back. If you have multiple items that match that query, they'll come back there.
[00:08:22]
This query set kind of acts like a list and you can treat it as one so you can call. Let's save this to a variable called results. You can call length on results. You can get the first item and results. Just like a list, this will throw an exception because we only have one item.
[00:08:43]
This throws list index out of range. The Django Orem It features a lot of optimizations under the hood. And the best part is you really don't need to know about the internal workings of databases to take full advantage of them.
Learn Straight from the Experts Who Shape the Modern Web
- In-depth Courses
- Industry Leading Experts
- Learning Paths
- Live Interactive Workshops