Django Models§
Storing and manipulating data with the Django ORM.
Storing and manipulating data with the Django ORM.
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.
}
}
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()
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()
objects
The filter
Manager method lets you perform queries:
Contact.objects.filter(last_name='Yergler')
filter
returns a QuerySet, an iterable over the result.
You can also assert you only expect one:
Contact.objects.get(first_name='Nathan')
If more than one is returned, an Exception will be raised
The full query reference is pretty good on this topic.
You can run the tests for your application using manage.py
:
(tutorial)$ python manage.py test
syncdb
manage command creates the tables in your database from modelstest
manage command runs the unit tests