Working with Django models Part-1

What are the Django models?

A model is the single, definitive source of information about your data. It contains the essential fields and behaviors of the data you’re storing. Generally, each model maps to a single database table.

  • Each model is a Python class that subclasses django.db.models.Model.
  • Each attribute of the model represents a database field.

Example

This example model defines a Profile, which has a first_namelast_name and bio:
from django.db import models

# Create your models here.

class Profile(models.Model):
    first_name = models.CharField(max_length=35)
    last_name = models.CharField(max_length=35)
    bio = models.TextField()

    def __str__(self):
      return self.first_name

 

Using models

Once you have defined your models, you need to tell Django you’re going to use those models. Do this by editing your settings file and changing the INSTALLED_APPS setting to add the name of the module that contains your models.py.

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    #profile app
    'profiles'
]

When you add new apps to INSTALLED_APPS, be sure to run manage.py migrate, optionally making migrations for them first with manage.py makemigrations.

Make sure you are in the same folder where manage.py file Exist, In this case.

djangotutes manage.py profiles
(env) [[email protected] djangotutes]$ python3 manage.py makemigrations
Migrations for 'profiles':
     profiles/migrations/0001_initial.py
      - Create model Profile
(env) [[email protected] djangotutes]$ python3 manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, profiles, sessions
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying admin.0003_logentry_add_action_flag_choices... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying auth.0009_alter_user_last_name_max_length... OK
  Applying auth.0010_alter_group_name_max_length... OK
  Applying auth.0011_update_proxy_permissions... OK
  Applying profiles.0001_initial... OK
  Applying sessions.0001_initial... OK

 

You can check migrated file under profiles app –> migrations –> 0001_initial.py

# Generated by Django 3.0.5 on 2020-04-11 11:18

from django.db import migrations, models


class Migration(migrations.Migration):

    initial = True

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Profile',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('first_name', models.CharField(max_length=35)),
                ('last_name', models.CharField(max_length=35)),
                ('bio', models.TextField()),
            ],
        ),
    ]


 

Auto-generate the models

Django comes with a utility called inspectdb that can create models by introspecting an existing database. You can view the output by running this command:

(env) [[email protected] djangotutes]$ python3 manage.py inspectdb

Save this as a file by using standard Unix output redirection:

(env) [[email protected] djangotutes]$ python3 manage.py inspectdb > models.py
  • This feature is meant as a shortcut, not as definitive model generation.
  • Once you’ve cleaned up your models, name the file models.py and put it in the Python package that holds your app. Then add the app to your INSTALLED_APPS setting.
  • By default, inspectdb creates unmanaged models. That is, managed = False in the model’s Meta class tells Django not to manage each table’s creation, modification, and deletion:
class Profile(models.Model):
    id = models.IntegerField(primary_key=True)
    first_name = models.CharField(max_length=35)
    class Meta:
       managed = False

If you do want to allow Django to manage the table’s lifecycle, you’ll need to change the managed option above to True (or remove it because True is its default value).

 

 

 

Leave a Reply