Basic Data Access

Once you’ve created a model, Django automatically provides a high-level Python API for working with those models. Try it out by running python manage.py shell from within your virtual environment and typing the following:

 >>> from books.models import Publisher
>>> p1 = Publisher(name='Apress', address='2855 Telegraph Avenue',
... city='Berkeley', state_province='CA', country='U.S.A.',
... website='http://www.apress.com/')
>>> p1.save()
>>> p2 = Publisher(name="O'Reilly", address='10 Fawcett St.',
... city='Cambridge', state_province='MA', country='U.S.A.',
... website='http://www.oreilly.com/')
>>> p2.save()
>>> publisher_list = Publisher.objects.all()
>>> publisher_list
<QuerySet [<Publisher: Publisher object>, <Publisher: Publisher object>]>

These few lines of code accomplish quite a bit. Here are the highlights:

  • First, we import our Publisher model class. This lets us interact with the database table that contains publishers.
  • We create a Publisher object by instantiating it with values for each field – name, address, etc.
  • To save the object to the database, call its save() method. Behind the scenes, Django executes an SQL INSERT statement here.
  • To retrieve publishers from the database, use the attribute Publisher.objects, which you can think of as a set of all publishers. Fetch a list of all Publisher objects in the database with the statement Publisher.objects.all(). Behind the scenes, Django executes an SQL SELECT statement here.

One thing is worth mentioning, in case it wasn’t clear from this example. When you’re creating objects using the Django model API, Django doesn’t save the objects to the database until you call the save() method:

p1 = Publisher(...)
# At this point, p1 is not saved to the database yet!
p1.save()
# Now it is.

If you want to create an object and save it to the database in a single step, use the objects.create() method. This example is equivalent to the example above:

>>> p1 = Publisher.objects.create(name='Apress',
... address='2855 Telegraph Avenue',
... city='Berkeley', state_province='CA', country='U.S.A.',
... website='http://www.apress.com/')
>>> p2 = Publisher.objects.create(name="O'Reilly",
... address='10 Fawcett St.', city='Cambridge',
... state_province='MA', country='U.S.A.',
... website='http://www.oreilly.com/')
>>> publisher_list = Publisher.objects.all()
>>> publisher_list 
<QuerySet [<Publisher: Publisher object>, <Publisher: Publisher object>]>

Naturally, you can do quite a lot with the Django database API – but first, let’s take care of a small annoyance.

Adding Model String Representations

When we printed out the list of publishers, all we got was this unhelpful display that makes it difficult to tell the Publisher objects apart:

<QuerySet [<Publisher: Publisher object>, <Publisher: Publisher object>]>

We can fix this easily by adding a method called __str__() to our Publisher class. A __str__() method tells Python how to display a human-readable representation of an object. You can see this in action by adding a __str__() method to the three models:

from django.db import models

class Publisher(models.Model):
name = models.CharField(max_length=30)
address = models.CharField(max_length=50)
city = models.CharField(max_length=60)
state_province = models.CharField(max_length=30)
country = models.CharField(max_length=50)
website = models.URLField()

def __str__(self):
return self.name

class Author(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=40)
email = models.EmailField()

def __str__(self):
return u'%s %s' % (self.first_name, self.last_name)

class Book(models.Model):
title = models.CharField(max_length=100)
authors = models.ManyToManyField(Author)
publisher = models.ForeignKey(Publisher)
publication_date = models.DateField()

def __str__(self):
return self.title

As you can see, a __str__() method can do whatever it needs to do in order to return a representation of an object. Here, the __str__() methods for Publisher and Book simply return the object’s name and title, respectively, but the __str__() for Author is slightly more complex – it pieces together the first_name and last_name fields, separated by a space. The only requirement for __str__() is that it return a string object. If __str__() doesn’t return a string object – if it returns, say, an integer – then Python will raise a TypeError with a message like:

TypeError: __str__ returned non-string (type int).

For the __str__() changes to take effect, exit out of the Python shell and enter it again with python manage.py shell. (This is the simplest way to make code changes take effect.) Now the list of Publisher objects is much easier to understand:

>>> from books.models import Publisher
>>> publisher_list = Publisher.objects.all()
>>> publisher_list
<QuerySet [<Publisher: Apress>, <Publisher: O'Reilly>]>

Make sure any model you define has a __str__() method – not only for your own convenience when using the interactive interpreter, but also because Django uses the output of __str__() in several places when it needs to display objects. Finally, note that __str__() is a good example of adding behavior to models. A Django model describes more than the database table layout for an object; it also describes any functionality that object knows how to do. __str__() is one example of such functionality – a model knows how to display itself.

 

Back to Tutorial

Installing the Model
Adding Model String Representations

Get industry recognized certification – Contact us

keyboard_arrow_up