Django Models§

Storing and manipulating data with the Django ORM.

Configuring Databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',  # 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'address.db',
        'USER': '',                      # Not used with sqlite3.
        'PASSWORD': '',                  # Not used with sqlite3.
        'HOST': '',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '',                      # Set to empty string for default. Not used with sqlite3.
    }
}

Defining Models

Models are created in the models module of a Django app and subclass Model

from django.db import models


class Contact(models.Model):

    first_name = models.CharField(
        max_length=255,
    )
    last_name = models.CharField(
        max_length=255,

    )

    email = models.EmailField()

Instantiating Models

nathan = Contact()
nathan.first_name = 'Nathan'
nathan.last_name = 'Yergler'
nathan.save()
nathan = Contact.objects.create(
    first_name='Nathan',
    last_name='Yergler')
nathan = Contact(
    first_name='Nathan',
    last_name='Yergler')
nathan.save()

Model Managers

Querying with Managers

Testing Models

Running the Tests

You can run the tests for your application using manage.py:

(tutorial)$ python manage.py test

Review§