Receive our weekly advanced programming tips for FREE
10.May
Create first model in django
0
| 0 votes
Autor: bookkeeper
Chapter: Django
To interact with the database we need a model in Django. This is a representation of a table in the database.

1. First we create a new app to separate the logic. Switch to apps folder and call django-admin.py startapp data

2. Switch to the new created folder "data"

3. Edit the file models.py

from django.db import models
class Entry(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    title   = models.CharField(max_length=64)
    text    = models.TextField()
    published = models.BooleanField(db_index=True, default=True)
    def __unicode__(self):
        return u"%s - %s" % (self.title, self.created) 


3.1 First we import the models module

3.2 When we create a new class Entry and it will inherit from models.Model class

3.3 Now we create attributes in the class, this will be our columns in the database

3.4 The module models has class fields, like DateTimeField, this will be a datetime column in the database, etc. If auto_add_now is True when the field will get a current datetime when it's created. If auto_now is add when the field will be updated with the current datetime

3.5 And and the end we create a __unicode__ method, a unicode representation of a model


4. Edit the global settings.py and set the right database settings

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'blog',                      # Or path to database file if using sqlite3.
        'USER': 'blog',                      # Not used with sqlite3.
        'PASSWORD': 'blog',                  # 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.
    }
}


5. Add the new app into INSTALLED_APPS

INSTALLED_APPS = (
    #...
    'apps.data',
    #....
)


6. Run python manage.py syncdb, now django will create all the tables with the right settings! You may create a superuser.



It can be that simple!