Models In Django-Free Django Tutorials

Objects in Django

In object-oriented programming there is a concept called object.The idea behind object is that instead of writing everything as a sequence programming instructions,we can model things and can also define how they interact with each other.

So object is a collection of actions and properties.Let’s understand it by example.

Suppose if we want to model a create,we will create an object Cat that has some properties associated with it like color,age and owner (which could be assigned a Person object – or maybe, in case of a stray cat, this property could be empty).
Cat has also some actions associated with it like purr,scratch or feed

Cat
--------
color
age
mood
owner
purr()
scratch()
feed(cat_food)
CatFood
--------
taste

So basically our idea is to describe real things in code with object properties and actions (called methods).


How will we model blog posts?

To answer this question,we need to first answer this question: What is a blog post? What properties a blog post should have?

Well, for sure our blog post needs some text with its main title and content.It will be nice if we also write who wrote it-the author name.We also want to know when the post was created and published.

Post
--------
title
text
author
created_date
published_date

We will  also need a publish method to publish a blog.

Django model

Now we have enough knowledge about object we can create a django model for our blog post.

A model is a special kind of object in django-that is saved in the database.A database is a normally a collection of data.A database is a place where we will store information about users and their blog posts etc.We will be using a SQLite database to store our data.SQLite database is the default django database adapter.

A user can also think of a model in the database as a spreadsheet with columns (fields) and rows (data).

Creating a blog post model

In the articles/models.py file which we have created in https://padhle.com/writing-your-first-blog-app-in-django-part-2/ .
we define all objects called Models – this is a place in which we will define our blog post.

We will write the articles/models.py file as following:

from django.db import models                                                  #line 1
from django.utils import timezone                                             #line 2


class Post(models.Model):                                                    #line 3
    author = models.ForeignKey('auth.User', on_delete=models.CASCADE)        #line 4
    title = models.CharField(max_length=200)                                 #line 5
    text = models.TextField()                                                #line 6
    created_date = models.DateTimeField(                                     #line 7
            default=timezone.now)                                            #line 8
    published_date = models.DateTimeField(                                   #line 9
            blank=True, null=True)                                           #line 10

    def publish(self):                                                       #line 11
        self.published_date = timezone.now()                                 #line 12
        self.save()                                                          #line 13
 
    def __str__(self):                                                       #line 14
        return self.title                                                    #line 15

Now let’s understand the above code line by line:

All lines in the code that are starting with from or import are the lines that add some contents from other files.So we don’t have to copy-paste the same things again and again in every file,we can include some parts with from … import …

class Post(models.Model): (line-3) -This line defines our model(basically it is an object):

  • class is a special keyword that indicates that user is defining an object.
  • Post is the name of our model.Always start a class name with an uppercase letter.
  • models.Model shows that the post is a django Model, so django knows that it should be saved in the database.

After that in the next following lines of code[line-4 to line-10] we are defining the properties of blog liketitle,content,created_date,
published_date and author.To define them we are defining type of each field.

  • models.CharField – this is for defining text with a limited number of characters.
  • models.TextField – this is for long text without a limit.
  • models.DateTimeField – this is for defining a date and time.
  • models.ForeignKey – this is a for defining a link to another model.

What about def publish(self):?
This is exactly the publish method we were talking about before. def means that this is a function or method in python and publish is the name of the method. You can change the name of the method according to your convienient.


Create tables for models in your database

The last step here is to add our new model we just created(post) to our database. First we have to make django know that we have some changes in our model or we have created a new model.For that go to command prompt and type python manage.py makemigrations blog

Django prepared a migration file for us  when we run the above command,that migration file we now have to apply to our database. For that go to command prompt and type  python manage.py migrate blog. Now Our Post model is now in our database.

For more information about models refer to this:https://docs.djangoproject.com/en/2.0/topics/db/models/


This is all about models in django and how to create and define models in django.

 

Leave a Comment

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