CE419 Web Programming Session 15: Django Web Framework
Web Applications & Databases In modern Web applications, the arbitrary logic often involves interacting with a database. Behind the scenes, a database-driven Web site connects to a database server, retrieves some data out of it, and displays that data on a Web page. The site might also provide ways for site visitors to populate the database on their own.
Web Applications & Databases Amazon.com, for instance, is a great example of a database-driven site. Each product page is essentially a query into Amazon s product database formatted as HTML. When you post a customer review, it gets inserted into the database of reviews. Django is well suited for making database-driven Web sites, because it comes with easy yet powerful tools for performing database queries using Python.
Databases: The Dumb Way import MySQLdb def book_list(request): db = MySQLdb.connect(user='me', db='mydb', passwd='secret', host='localhost') cursor = db.cursor() 3 2 cursor.execute('select name FROM books ORDER BY name') names = [row[0] for row in cursor.fetchall()] db.close() 1 # let's do the rest here.
Databases: The Not-So-Dumb Way ORM comes to the rescue! from mysite.books.models import Book def book_list(request): books = Book.objects.order_by('name') # tada!
Models in Django A model is the single, definitive source of information about your data. It contains the essential fields and behaviors of the data you re storing. Generally, each model maps to a single database table. Each model is a Python class that subclasses django.db.models.model. Each attribute of the model represents a database field.
Configuring the Database First, we need to take care of some initial configuration; we need to tell Django which database server to use and how to connect to it. settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.', 'NAME': '', 'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': '', } }
SQLite In contrast to other database management systems, SQLite is not a client server database engine. Rather, it is embedded into the end program. Good for development and small projects.
Quick Example from django.db import models class Person(models.Model): first_name = models.charfield(max_length=30) last_name = models.charfield(max_length=30) CREATE TABLE myapp_person ( "id" serial NOT NULL PRIMARY KEY, "first_name" varchar(30) NOT NULL, "last_name" varchar(30) NOT NULL );
Using Models Once you have defined your models, you need to tell Django you re going to use those models. Do this by editing your settings file and changing the INSTALLED_APPS setting to add the name of the module that contains your models.py. INSTALLED_APPS = ( #... 'myapp', #... ) python manage.py migrate
Fields The most important part of a model and the only required part of a model is the list of database fields it defines. Fields are specified by class attributes. from django.db import models class Post(models.Model): title = models.charfield(max_length=255) body = models.textfield() author = models.foreignkey(user) publish_date = models.datetimefield()
Field Types Each field in your model should be an instance of the appropriate Field class. Some of builtin field types in Django: CharField, TextField, DateField, DateTimeField, EmailField, FileField, URLField, etc. Complete list: https://docs.djangoproject.com/en/1.8/ref/models/ fields/ You can subclass Field and create your custom types! For example, PersianDateField.
Field Options Each field takes a certain set of field-specific arguments. CharField requires max_length. There s also a set of common arguments available to all field types. All are optional.
Field Options (cont'd) null If True, Django will store empty values as NULL in the database. Default is False. blank If True, the field is allowed to be blank. Default is False. Difference between blank and null?
Field Options (cont'd) default The default value for the field. This can be a value or a callable object. unique If True, this field must be unique throughout the table.
Field Options (cont'd) import datetime from django.db import models class Post(models.Model): # title = models.charfield(max_length=255, unique=true) excerpt = models.textfield(null=true, blank=true) publish_date = models.datetimefield(default=datetime.datetime.now) #
Automatic Primary Key Fields By default, Django gives each model the following field: id = models.autofield(primary_key=true) If you d like to specify a custom primary key, just specify primary_key=true on one of your fields. If Django sees you ve explicitly set Field.primary_key, it won t add the automatic id column.
Relationships Clearly, the power of relational databases lies in relating tables to each other. Django offers ways to define the three most common types of database relationships: many-to-one, many-tomany and one-to-one.
Many-to-One Relationships from django.db import models class Manufacturer(models.Model): #... pass class Car(models.Model): manufacturer = models.foreignkey(manufacturer) #... 2 1
Many-to-Many Relationships It doesn t matter which model has the ManyToManyField, but you should only put it in one of the models not both. "More Natural" from django.db import models class Track(models.Model): #... pass class Playlist(models.Model): tracks = models.manytomanyfield(track) #... 2 1
One-to-One Relationships For example, if you were building a database of places, you would build pretty standard stuff such as address, phone number, etc. in the database. Then, if you wanted to build a database of restaurants on top of the places, instead of repeating yourself and replicating those fields in the Restaurant model, you could make Restaurant have a OneToOneField to Place.
Making Database Queries Once you ve created your data models, Django automatically gives you a database-abstraction API that lets you create, retrieve, update and delete (CRUD) objects. A model class represents a database table, and an instance of that class represents a particular record in the database table. python manage.py shell
Creating Objects To create an object, instantiate it using keyword arguments to the model class, then call save() to save it to the database. from blog.models import Author author = Author(name="Sadjad Fouladi", email="sfouladi@gmail.com") author.save() 2 1 author.email = "fouladi@ce.sharif.edu" author.save() 3
Saving ForeignKey and ManyToManyField Fields Updating a ForeignKey field works exactly the same way as saving a normal field simply assign an object of the right type to the field in question. Updating a ManyToManyField works a little differently use the add() method on the field to add a record to the relation.
Retrieving Objects To retrieve objects from your database, construct a QuerySet via a Manager on your model class. A QuerySet represents a collection of objects from your database. It can have zero, one or many filters. In SQL terms, a QuerySet equates to a SELECT statement, and a filter is a limiting clause such as WHERE or LIMIT.
Retrieving Objects (cont'd) Retrieving all objects all_entries = Entry.objects.all() Filtering and excluding q1 = Entry.objects.filter(rating=4) q2 = Entry.objects.exclude(rating lt=3) q3 = Entry.objects.filter(headline contains='book', rating=5, pub_date year=2011)
Chaining Filters The result of refining a QuerySet is itself a QuerySet, so it s possible to chain refinements together. q1 = Entry.objects.filter( rating=4 ).filter( headline contains="book" ).exclude( pub_date year=2013 )
Querysets Are Lazy >>> q = Entry.objects.filter(headline startswith="what") >>> q = q.filter(pub_date lte=datetime.date.today()) >>> print(q) 29
Retrieving a Single Object DoesNotExist, MultipleObjectsReturned. one_entry = Entry.objects.get(id=1)
Limiting QuerySets What if the QuerySet matches 1,000 objects?! Entry.objects.all()[:5] Entry.objects.filter( )[15:30] Equivalent of SQL s LIMIT and OFFSET clauses.
Field Lookups Field lookups are how you specify the meat of an SQL WHERE clause. They re specified as keyword arguments to the QuerySet methods filter(), exclude() and get(). field lookuptype=value exact, iexact, contains, icontains, startswith, endswith, lt, gt, lte, gte, and A LOT more.
Deleting and Updating Objects Entry.objects.filter( rating=4 ).update(rating=5) Entry.objects.filter(rating lte=2).delete()
Django Admin One of the most powerful parts of Django is the automatic admin interface. Let's see Django admin for our project!
Thank you. Any questions? 38