Your next step is to put data in your database. For this, you’re going to use the Django shell to put one project in your database. Head over to your terminal and start the Django shell by typing the following:
$ python manage.py shell
This opens up a terminal, but it has the Django settings already imported, so it allows you to work directly from the root folder of a Django project.
Next, we want to put some data into our database. For this, we’re going to use the Django shell. There’s some different ways of doing that, but I want to show you this very handy tool. We’re going to get started and put one
Project into our database.
However, it has the Django settings already imported, so it allows you to work directly from the root folder of a Django project. So, if you want to do something within Django or with the database, then start your shell like this. Now, what I want to do is I want to create a
Project object and put this one into the database. For this, I’m going to use Django’s ORM. So, here is our cheatsheet.
We can find this inside of—let me close this for a moment—
projects/ and then
models.py. Okay, so this is where it sits. I’m going to say
from projects.models import Project, and now I can create a
Yada, yada, I’m just going to fill this out. Make sure that you put in the right data types. Like, it’s clear that we’re going to use text for a
CharField (character field),
TextField, and you can’t go over the
max_length or it’s going to complain, et cetera.
Cool. So, all done? Not quite. What we need to do first—similar to the migrations—there’s always a step in between before you actually commit something to the database. So what I need to do to put it into the database is I have to say
And now, I have this one instance as a row sitting inside of my database. We can inspect this with this visual tool that I showed you before, go ahead and do that. I’m going to show you a different way of doing it, which is I can query here. So, I can say
results = Project.objects.all().
I can say
p.title, for example, and this is
'test project'. It’s what I just put in there—so, what I did. And that’s where we can see the power of using an object-relational mapper. Using Python, I created an object, then I simply said
.save() to put it into my relational database, and here I’m—again—using the ORM to query the database, get some results back, and then you can see, I can access them again very similar—or, in the same way that I would access a Python object.
So that’s the ORM at work, and yeah, we put a
Project inside of our database. So, let’s make sure to set up the rest that we need. We still need routes, we need views, and we need templates. Let’s make sure to set those up so that we can actually see this
Project, also on the front end.
Become a Member to join the conversation.