Home > Django, Framework > Create Django App and Data Model

Create Django App and Data Model

Creating Django App

To manage a project, django divide the project into several small django apps. Django app is a group of related functionality used to complete or maintain one aspect of a site.

The following command will create django app called myapp

$ python manage.py startapp myapp

To make django load the app, we need to add app name in django setting:

$ nano mysite/settings.py
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    # project app
    'myapp'
]

Creating Data Model

We often need to store our data into database. In django, we need to define our data model first, then make django to propagate data model creation/changes to database schema by using django commands. In this example, we will create data model inside of django app that we created before.

  1. Create data model
    $ nano myapp/models.py
    # -*- coding: utf-8 -*-
    from __future__ import unicode_literals
    from django.db import models
    
    class MyModel(models.Model):
        foo = models.IntegerField(default=0)
        bar = models.TextField(blank=True, null=True)
    
        class Meta:
            db_table = 'my_model_tbl'
  2. Make django migration
    $ python manage.py makemigrations myapp
  3. Apply changes to database schema
    $ python manage.py migrate myapp

     

Advertisements
Categories: Django, Framework
  1. May 14, 2017 at 5:53 am

    Thanks for the type. I can see how dividing a single application into smaller applications can be really helpful!

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: