Let us know about model in django

Creating a Model


Django models map (roughly) to a database table, and provide a place to encapsulate business logic. All models subclass the base Model class, and contain field definitions. Let’s start by creating a simple Contact model for our application in contacts/models.py.
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()

    def __str__(self):

        return ' '.join([
            self.first_name,
            self.last_name,
        ])
Django provides a set of fields that map to data types and different validation rules. For example, the EmailField here maps to the same column type as the CharField, but adds validation for the data.
Once you’ve created a model, you need to update your database with the new tables. Django’s syncdb command looks for models that are installed and creates tables for them if needed.
(tutorial)$ python ./manage.py syncdb

Creating tables ...
Creating table auth_permission
Creating table auth_group_permissions
Creating table auth_group
Creating table auth_user_user_permissions
Creating table auth_user_groups
Creating table auth_user
Creating table django_content_type
Creating table django_session
Creating table django_site

...
Our contact table isn’t anywhere to be seen. The reason is that we need to tell the Project to use the Application.
The INSTALLED_APPS setting lists the applications that the project uses. These are listed as strings that map to Python packages. Django will import each and looks for a models module there. Add our Contacts app to the project’s INSTALLED_APPS setting:
INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # Uncomment the next line to enable the admin:
    # 'django.contrib.admin',
    # Uncomment the next line to enable admin documentation:
    # 'django.contrib.admindocs',
    'contacts',
)
Then run syncdb again:
(tutorial)$ python ./manage.py syncdb
Creating tables ...
Creating table contacts_contact
Installing custom SQL ...
Installing indexes ...
Installed 0 object(s) from 0 fixture(s)
Note that Django created a table named contacts_contact: by default Django will name your tables using a combination of the application name and model name. You can override that with the model Meta options.

Interacting with the Model

Now that the model has been synced to the database we can interact with it using the interactive shell.
(tutorial)$ python ./manage.py shell
Python 2.7.3 (default, Aug  9 2012, 17:23:57)
[GCC 4.7.1 20120720 (Red Hat 4.7.1-5)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from contacts.models import Contact
>>> Contact.objects.all()
[]
>>> Contact.objects.create(first_name='Nathan', last_name='Yergler')
<Contact: Nathan Yergler>
>>> Contact.objects.all()
[<Contact: Nathan Yergler>]
>>> nathan = Contact.objects.get(first_name='Nathan')
>>> nathan
<Contact: Nathan Yergler>
>>> print nathan
Nathan Yergler
>>> nathan.id
1
There are a few new things here. First, the manage.py shell command gives us a interactive shell with the Python path set up correctly for Django. If you try to run Python and just import your application, an Exception will be raised because Django doesn’t know which settings to use, and therefore can’t map Model instances to the database.
Second, there’s this objects property on our model class. That’s the model’s Manager. If a single instance of a Model is analogous to a row in the database, the Manager is analogous to the table. The default model manager provides querying functionality, and can be customized. When we call all() or filter() or the Manager, a QuerySet is returned. A QuerySet is iterable, and loads data from the database as needed.
Finally, there’s this id field that we didn’t define. Django adds an id field as the primary key for your model, unless you specify a primary key.

No comments:

Post a Comment