Basic App Model - Makemigrations and Migrate

Basic App Model - Makemigrations and Migrate

Django uses its Object-Relational Mapping (ORM) system to interact with the database. The process of creating or updating your database schema based on changes in your models is done through migrations. This tutorial will guide you through creating a basic app model, then using makemigrations and migrate to reflect the model changes in the database.

Step 1: Create a New App

Let's create a new app called blog.

python manage.py startapp blog

Step 2: Define a Basic Model

Navigate to the models.py file in the newly created blog app and define a model for a Post.

# blog/models.py

from django.db import models

class Post(models.Model):
    title = models.CharField(max_length=200)
    content = models.TextField()
    date_created = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.title

Step 3: Register the App with the Project

Make sure the new blog app is added to the INSTALLED_APPS list in the project's settings.py:

# settings.py

INSTALLED_APPS = [
    # ...
    'blog',
]

Step 4: Create Migrations

After defining your model, it's time to let Django prepare a migration for it.

python manage.py makemigrations blog

This command tells Django to create a new migration based on the changes detected in the blog app's models. Django will generate a migration file in the blog/migrations/ directory.

Step 5: Apply Migrations

Now that you've created the migration, it's time to apply it to the database with:

python manage.py migrate

This command looks at the MIGRATION_MODULES setting and synchronizes the database state with the current models and existing migrations. Essentially, it creates the Post table in your database.

Step 6: Verify Changes

  1. Check Migration Status: You can check which migrations have been applied using:

    python manage.py showmigrations
    

    Look under the blog section, and you should see your migration with an [X] next to it, indicating it has been applied.

  2. Django Admin: If you've set up the Django admin, you can register the Post model and view the table there.

In blog/admin.py:

from django.contrib import admin
from .models import Post

admin.site.register(Post)

Start the development server with python manage.py runserver, navigate to the admin site, and you should see the Post model listed under the blog app.

Conclusion

Migrations are a powerful feature in Django, allowing you to change your database schema without having to drop and recreate tables. The makemigrations command prepares these changes, and the migrate command applies them. This two-step process ensures you have a chance to review changes before applying them, giving you control over database alterations.


More Tags

xcode10beta6 is-empty preprocessor bin-packing tidyverse uninstallation void terminology angularjs-ng-change client-side

More Programming Guides

Other Guides

More Programming Examples