Creating Python APIs - The Django REST framework. Building a Reddit clone - Models.[2/n]

Rest-API-introduction.jpg

This is the 2nd part of the Creating Python API series, If you haven't read the 1st article go read about it here.

Let's begin!

I believe the best way to learn is by doing so we're going to be making our own reddit clone in this article.

We'll not be making a full fledged Reddit clone with all its features, rather we will be making a simpler version of it. We will create a service where people post links and upvote them using Django and making an API for it.

Creating the Django app

A) Open your terminal and go to your desktop (or any preferred location where you want to save the project).

Use the command: cd Desktop

B) Create the project using the command: django-admin startproject reddit

I used reddit, you can name the app anything you like.

I later change the project name manually from reddit to reddit-project because it makes it easier to distinguish the top level folder.

C) You can check if it has all been created properly by using the command: python manage.py runserver (It can be Python/Python3 depending on the version of Python you have installed on your computer. I have only Python3 installed so even if I use Python it knows I mean Python3. If you have both the versions installed you would need to explicitly specify the python version).

You should see the following in your terminal.

runserver.jpg

And the following in your browser.

installedsuccess.jpg

This means we've followed the steps correctly, now we can move on to create the Posts app.

D) Since we will be having posts in our service we need to create a Posts app by running the command: python manage.py startapp posts

Open the folder using your favorite code editor - I use vscode. You'd see the following folder structure.

posts.jpg

E) After creating the posts app, add it in the settings.py under installed apps as below:

image.png

F) Then go to the models.py and type the following code:

image.png

Explanation of each line is under the line in the comments.

G) After creating the model we need to migrate the model by using the command (Remember to always migrate the model after you make any changes to it )

python manage.py makemigrations

You should see the following:

image.png

which means there was no error in making migrations. We can successfully migrate now using the command python manage.py migrate

You should see the following:

image.png

This updates the database for us. This was a very big first step to get the project started but we have a strong foundation now and we can start building this thing.

Hope you enjoyed this post! If you happen to like it, feel free to share. You can also follow me on Twitter on my coding journey.