Creating Django Models and their Tables in the database(Part V)

In this tutorial, we will further dive deep down with the concepts of Django Models and create some of them for our blog application. Then finally we will save those Models using tables in the database.

This tutorial is a part of our series on Creating Blog Website using Django.

Link to the Previous tutorial:

Creating Django Application and Introduction to Django Models(Part IV)

Creating a Post model for our Blog

There is a file blog1/models.py in our application directory and this is the place where we define all of our Models.

Open this file, remove everything and copy the below-provided code:

from django.conf import settings
from django.db import models


class Post(models.Model):
    author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    title = models.CharField(max_length=100)
    text = models.TextField()
    published_date = models.DateTimeField(blank=True)

    def publish(self):
        self.published_date = timezone.now()
        self.save()

    def __str__(self):
        return self.title

Now, let us get on to the explanation of this huge code.



‘class’ keyword defines an object with the given name ‘post‘, including models.model to turn this object in a framework for further posts.

Then we have few attributes for our object author, title, text and published_date.

Moving on, we have defined a function publish() which does the job of publishing the post on the website.

Save the above file and it will create a model for our Application.

Creating Django Tables to save Model’s data in the database

Since we are using SQL database to save our data, we need to save it in the form of tables as SQL is a Relational Database Management System.

So, to turn the data of models in the form of tables, run the command :

python manage.py makemigrations blog1

And to finally save that in the Database, run :

python manage.py migrate blog1

That’s it!

If you face any query feel free to drop it in the comments section.

Next part of this tutorial series:

How to create a Django SuperUser and a look at Django Admin (Part VI)

 

Further, look for some other posts :

How to add a number to each element in a list in Python

Scrapping the data of webpage using XPath in scrapy

Leave a Reply

Your email address will not be published. Required fields are marked *