Django models

Django models

A model in Django is a special kind of object - it is saved in the database.You can think of a model in the database as a spreadsheet(table)  with columns (fields) and rows (data).


Creating an application

To keep everything tidy, we will create a separate application inside our project.

To create an application we need to run the following command in the console (from djangogirls directory where manage.py file is):

(myvenv) ~/djangogirls$ python manage.py statapp blog



That’ll create a directory blog, which is laid out like this:

blog/

    __init__.py

    admin.py

    apps.py

    migrations/

        __init__.py

    models.py

    tests.py

    views.py

After creating an application we also need to tell Django that it should use it. We do that in the file mysite/settings.py. We need to find INSTALLED_APPS and add a line containing 'blog', just above ). So the final product should look like this:



Creating a blog post model


In the blog/models.py file we define all objects called Models - this is a place in which we will define our blog post.

Let's open blog/models.py, remove everything from it and write code like this:

from django.db import models
from django.utils import timezone


class Post(models.Model):
    author = models.ForeignKey('auth.User')

    title = models.CharField(max_length=200)

    text = models.TextField()

    created_date = models.DateTimeField(
            default=timezone.now)

    published_date = models.DateTimeField(
            blank=True, null=True)

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

    def __str__(self):
        return self.title

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

class is a special keyword that indicates that we are defining an object.

 Post is the name of our model. We can give it a different name (but we must avoid special characters and whitespaces). Always start a class name with an uppercase letter.

 models.Model means that the Post is a Django Model, so Django knows that it should be saved in the database.

Now we define the properties we were talking about: title, text, created_date, published_date and author.

 models.CharField - this is how you define text with a limited number of characters.

  models.TextField - this is for long text without a limit. Sounds ideal for blog post content, right?

  models.DateTimeField - this is a date and time.

  models.ForeignKey - this is a link to another model.



def publish(self):? It is exactly the publish method we were talking about before. def means that this is a function/method and publish is the name of the method



Methods often return something. There is an example of that in the __str__ method. In this scenario, when we call __str__() we will get a text (string) with a Post title.


Create tables for models in your database


The last step here is to add our new model to our database. First we have to make Django know that we have some changes in our model (we have just created it!). Go to your console window and type

python manage.py makemigrations blog


Django prepared for us a migration file that we have to apply now to our database. Type

python manage.py migrate blog


Hurray! Our Post model is now in our database! It would be nice to see it, right?


Django command-line utility to create the database tables automatically:
    python manage.py migrate

The migrate command looks at all your available models and creates tables in your database for whichever tables don’t already exist .

The migrate command looks at the INSTALLED_APPS setting and creates any necessary database tables according to the database settings in your mysite/settings.py file The migrate command will only run migrations for apps in INSTALLED_APPS.


By running makemigrations, you’re telling Django that you’ve made some changes to your models (in this case, you’ve made new ones) and that you’d like the changes to be stored as a migration.

here’s a command that will run the migrations for you and manage your database schema automatically - that’s called migrate


    Change your models (in models.py).
    Run python manage.py makemigrations to create migrations for those changes
    Run python manage.py migrate to apply those changes to the database.
 

0 comments:

Copyright © 2013 SoftKul