Previous Page Next Page

Part II: Implementing the Website Interface

 

HOUR 5 Using Data from the Database in Views

 

HOUR 6 Configuring Web Page Views

 

HOUR 7 Implementing Django Templates to Create Custom Views

 

HOUR 8 Using Built-in Template Tags to Enhance Views

 

HOUR 9 Using Built-in Template Filters to Enhance Views

 

HOUR 10 Adding Forms to Views

 

HOUR 11 Using Views to Add and Update Data in the Database

 

HOUR 12 Utilizing Generic Views

 

HOUR 13 Advanced View Configurations

Hour 5. Using Data from the Database in Views

What You'll Learn in This Hour

  • How to add objects to the SQL database

  • How to access objects in the SQL database

  • How to modify objects and update the SQL database

  • How to perform complex queries on the SQL database

  • How to apply data from the database in views

Django provides a valuable database-abstraction application programming interface (API) that allows you to create, retrieve, update, and delete objects in the database using Python code rather than SQL requests.

The database-abstraction API is automatically added to the models you create in the models.py file. As you will see in the following sections, you can access the API methods used to create, modify, and query objects in the SQL database directly from the model object.

In this hour, we will explore using this API to add, modify, and access objects in the database using the model object defined in the models.py file.

Adding Data to the Database

Adding entries to the SQL database using the Django database-abstraction API is a simple process. The basic steps involve importing the object class from the model, creating a new object, and then using the database-abstraction function save() to save the object to the database.

Although the process itself is rather simple, the amount of work necessary depends on how complex your objects are. Simple objects with only a few text type fields are easy to create. For example, consider adding an object for the Blog class in the models.py file:

class Blog(models.Model):
    title = models.CharField('Title', max_length=200)
    text = models.TextField('Text', max_length=2048)

The first step in adding an object to the database is to import the object class from the model using the following line of code in the Django shell:

from iFriends.People.models import Blog

After the object class has been imported, you can use the class constructor to create a new Blog object using the following line of code:

b = Blog(title='MyBlog1', text = 'My Blog Entry')

A new Blog object is created and assigned to b. Then you can use the save() function to save the new object in the SQL database, as shown in the following line of code:

b.save()

Did you Know?

Django provides a create() function in the database-abstraction API that automatically creates the object in the database without you having to use the save() function. In the preceding example, we could have saved a step by using the following single line of code:

b = Blog.create(title='MyBlog1', text = 'My Blog Entry')


Now let's look at creating a new object for a more complex class listed in the following code snippet:

class Blog(models.Model):
    userID = models.ForeignKey(User, unique=True)
    title = models.CharField('title', max_length=200)
    date = models.DateField('Date', blank=True, null=True)
    text = models.TextField('Text', max_length=2048)

This example contains a couple different problems. The first is that there are too many fields to reasonably create the object using a single line of code. The second is that the userID field requires a django.contrib.auth.models.User object, not a string or number. The third is that the date field requires a Python datetime object.

To overcome these problems, you would first create a blank object:

b = Blog()

A new blank Blog object is created and assigned to b. You would use the following code snippet to add the title and text fields to the Blog object:

b.title='MyBlog1'
b.text = 'My Blog Entry'

Then you would use the following Python code to access the first django.contrib.auth.models.User object and assign it to the userID field:

from django.contrib.auth.models import User
b.userID = User.objects.get(id=1)

Finally, you would use the following code to assign the current time to the date field:

from datetime import datetime
b.date = datetime.now()

After you have added all the fields to the object, you can add the object to the database using the following line of code:

b.save()

Watch Out!

If you set the primary key value when creating a new object, you must make certain that it doesn't already exist in the database. If the key already exists, the existing object is overwritten with the new one.


Try It Yourself: Add an Object to the SQL Database

In this section, you will use the Django shell to add a Person object to the People table in the SQL database.

Follow these steps to create a Person object, populate the data in the Person object's fields, and then save the object in the database:

1.
Because we will add a Person object, we need to use the Django admin interface to create a new user object first. Access the admin interface at the following web address:

http://127.0.0.1:8000/admin/

2.
Click the Add link next to Users to bring up the dialog box shown in Figure 5.1.

Figure 5.1. The Add user page in the Django admin interface.


3.
Add a new user object with the username King_Arthur, and give it the password test.

4.
Save the user by clicking the Save button.

5.
Now we are ready to create the new Person object using the Django shell. From a command prompt, navigate to the root of the iFriends project.

6.
Open the Django shell using the following command:

python manage.py shell

7.
From the Django shell, import the Person class using the following command:

from iFriends.People.models import Person

8.
Create a blank Person object using the following command:

p = Person()

9.
Use the following commands to assign the userID field of the Person object to the King_Arthur object you created in step 3:

from django.contrib.auth.models import User
p.userID = User.objects.get(username='King_Arthur')

10.
Use the following commands to assign the birthday field of the Person object to a proper date:

from datetime import datetime
p.birthday = datetime(2000, 1, 1)

11.
Assign the rest of the necessary fields, shown in Listing 5.1, using the following commands:

p.name = 'King Arthur'
p.gender = 'M'
p.email = 'kingofthebrits@camelot.com'
p.favoriteURL = 'http://www.camelot.com'
p.desc = 'King of the Brits'

12.
Save the new Person object to the SQL database using the following command:

p.save()

Listing 5.1 shows the complete models.py file.

Listing 5.1. Full Contents of the iFriends\People\models.py File

from django.db import models
from django.contrib.auth.models import User

gender_list = (('M', 'Male'), ('F', 'Female' ))

class Blog(models.Model):
    title = models.CharField('Title', max_length=200)
    text = models.TextField('Text', max_length=2048)

class Person(models.Model):
    userID = models.ForeignKey(User, unique=True)
    name = models.CharField('name', max_length=200)
    birthday = models.DateField('Birthday', blank=True, null=True)
    gender = models.CharField(max_length=1, choices=gender_list)
    email = models.EmailField('Email', max_length=100, unique=True)
    favoriteURL = models.URLField('myURL')
    desc = models.TextField('Desc', max_length=500, null=True)
    friends = models.ManyToManyField('self', blank=True)
    blogs = models.ManyToManyField(Blog, blank=True)

    def __str__(self):
        return '%s' % (self.name)

    class Admin:
       pass


Previous Page Next Page