web programming session 15: django web...

34
CE419 Web Programming Session 15: Django Web Framework

Upload: others

Post on 29-May-2020

3 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Web Programming Session 15: Django Web Frameworkce.sharif.edu/.../root/Slides/S15-Django-Models.pdf · 2016-05-10 · Web Applications & Databases • In modern Web applications,

CE419 Web Programming Session 15: Django Web Framework

Page 2: Web Programming Session 15: Django Web Frameworkce.sharif.edu/.../root/Slides/S15-Django-Models.pdf · 2016-05-10 · Web Applications & Databases • In modern Web applications,

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.

Page 3: Web Programming Session 15: Django Web Frameworkce.sharif.edu/.../root/Slides/S15-Django-Models.pdf · 2016-05-10 · Web Applications & Databases • In modern Web applications,

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.

Page 4: Web Programming Session 15: Django Web Frameworkce.sharif.edu/.../root/Slides/S15-Django-Models.pdf · 2016-05-10 · Web Applications & Databases • In modern Web applications,

Databases: The Dumb Way

import MySQLdb

def book_list(request): db = MySQLdb.connect(user='me', db='mydb', passwd='secret', host='localhost') cursor = db.cursor() cursor.execute('SELECT name FROM books ORDER BY name') names = [row[0] for row in cursor.fetchall()] db.close()

# let's do the rest here.

1

23

Page 5: Web Programming Session 15: Django Web Frameworkce.sharif.edu/.../root/Slides/S15-Django-Models.pdf · 2016-05-10 · Web Applications & Databases • In modern Web applications,

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!

Page 6: Web Programming Session 15: Django Web Frameworkce.sharif.edu/.../root/Slides/S15-Django-Models.pdf · 2016-05-10 · Web Applications & Databases • In modern Web applications,

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.

Page 7: Web Programming Session 15: Django Web Frameworkce.sharif.edu/.../root/Slides/S15-Django-Models.pdf · 2016-05-10 · Web Applications & Databases • In modern Web applications,

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': '', } }

Page 8: Web Programming Session 15: Django Web Frameworkce.sharif.edu/.../root/Slides/S15-Django-Models.pdf · 2016-05-10 · Web Applications & Databases • In modern Web applications,

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.

Page 9: Web Programming Session 15: Django Web Frameworkce.sharif.edu/.../root/Slides/S15-Django-Models.pdf · 2016-05-10 · Web Applications & Databases • In modern Web applications,

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 );

Page 10: Web Programming Session 15: Django Web Frameworkce.sharif.edu/.../root/Slides/S15-Django-Models.pdf · 2016-05-10 · Web Applications & Databases • In modern Web applications,

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.

python manage.py migrate

INSTALLED_APPS = ( #... 'myapp', #... )

Page 11: Web Programming Session 15: Django Web Frameworkce.sharif.edu/.../root/Slides/S15-Django-Models.pdf · 2016-05-10 · Web Applications & Databases • In modern Web applications,

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()

Page 12: Web Programming Session 15: Django Web Frameworkce.sharif.edu/.../root/Slides/S15-Django-Models.pdf · 2016-05-10 · Web Applications & Databases • In modern Web applications,

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.

Page 13: Web Programming Session 15: Django Web Frameworkce.sharif.edu/.../root/Slides/S15-Django-Models.pdf · 2016-05-10 · Web Applications & Databases • In modern Web applications,

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.

Page 14: Web Programming Session 15: Django Web Frameworkce.sharif.edu/.../root/Slides/S15-Django-Models.pdf · 2016-05-10 · Web Applications & Databases • In modern Web applications,

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?

Page 15: Web Programming Session 15: Django Web Frameworkce.sharif.edu/.../root/Slides/S15-Django-Models.pdf · 2016-05-10 · Web Applications & Databases • In modern Web applications,

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.

Page 16: Web Programming Session 15: Django Web Frameworkce.sharif.edu/.../root/Slides/S15-Django-Models.pdf · 2016-05-10 · Web Applications & Databases • In modern Web applications,

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) # …

Page 17: Web Programming Session 15: Django Web Frameworkce.sharif.edu/.../root/Slides/S15-Django-Models.pdf · 2016-05-10 · Web Applications & Databases • In modern Web applications,

Automatic Primary Key Fields

• By default, Django gives each model the following field:

• 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.

id = models.AutoField(primary_key=True)

Page 18: Web Programming Session 15: Django Web Frameworkce.sharif.edu/.../root/Slides/S15-Django-Models.pdf · 2016-05-10 · Web Applications & Databases • In modern Web applications,

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-to-many and one-to-one.

Page 19: Web Programming Session 15: Django Web Frameworkce.sharif.edu/.../root/Slides/S15-Django-Models.pdf · 2016-05-10 · Web Applications & Databases • In modern Web applications,

Many-to-One Relationships

from django.db import models

class Manufacturer(models.Model): # ... pass

class Car(models.Model): manufacturer = models.ForeignKey(Manufacturer) # ...

1

2

Page 20: Web Programming Session 15: Django Web Frameworkce.sharif.edu/.../root/Slides/S15-Django-Models.pdf · 2016-05-10 · Web Applications & Databases • In modern Web applications,

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) # ...

1

2

Page 21: Web Programming Session 15: Django Web Frameworkce.sharif.edu/.../root/Slides/S15-Django-Models.pdf · 2016-05-10 · Web Applications & Databases • In modern Web applications,

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.

Page 22: Web Programming Session 15: Django Web Frameworkce.sharif.edu/.../root/Slides/S15-Django-Models.pdf · 2016-05-10 · Web Applications & Databases • In modern Web applications,

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

Page 23: Web Programming Session 15: Django Web Frameworkce.sharif.edu/.../root/Slides/S15-Django-Models.pdf · 2016-05-10 · Web Applications & Databases • In modern Web applications,

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="[email protected]") author.save()

author.email = "[email protected]" author.save()

1

2

3

Page 24: Web Programming Session 15: Django Web Frameworkce.sharif.edu/.../root/Slides/S15-Django-Models.pdf · 2016-05-10 · Web Applications & Databases • In modern Web applications,

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.

Page 25: Web Programming Session 15: Django Web Frameworkce.sharif.edu/.../root/Slides/S15-Django-Models.pdf · 2016-05-10 · Web Applications & Databases • In modern Web applications,

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.

Page 26: Web Programming Session 15: Django Web Frameworkce.sharif.edu/.../root/Slides/S15-Django-Models.pdf · 2016-05-10 · Web Applications & Databases • In modern Web applications,

Retrieving Objects (cont'd)

• Retrieving all objects

• Filtering and excluding

all_entries = Entry.objects.all()

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)

Page 27: Web Programming Session 15: Django Web Frameworkce.sharif.edu/.../root/Slides/S15-Django-Models.pdf · 2016-05-10 · Web Applications & Databases • In modern Web applications,

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 )

Page 28: Web Programming Session 15: Django Web Frameworkce.sharif.edu/.../root/Slides/S15-Django-Models.pdf · 2016-05-10 · Web Applications & Databases • In modern Web applications,

Querysets Are Lazy

>>> q = Entry.objects.filter(headline__startswith="What")>>> q = q.filter(pub_date__lte=datetime.date.today())>>> print(q)

�29

Page 29: Web Programming Session 15: Django Web Frameworkce.sharif.edu/.../root/Slides/S15-Django-Models.pdf · 2016-05-10 · Web Applications & Databases • In modern Web applications,

Retrieving a Single Object

• DoesNotExist, MultipleObjectsReturned.

one_entry = Entry.objects.get(id=1)

Page 30: Web Programming Session 15: Django Web Frameworkce.sharif.edu/.../root/Slides/S15-Django-Models.pdf · 2016-05-10 · Web Applications & Databases • In modern Web applications,

Limiting QuerySets

• What if the QuerySet matches 1,000 objects?!

• Equivalent of SQL’s LIMIT and OFFSET clauses.

Entry.objects.all()[:5] Entry.objects.filter(…)[15:30]

Page 31: Web Programming Session 15: Django Web Frameworkce.sharif.edu/.../root/Slides/S15-Django-Models.pdf · 2016-05-10 · Web Applications & Databases • In modern Web applications,

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().

• exact, iexact, contains, icontains, startswith, endswith, lt, gt, lte, gte, and A LOT more.

field__lookuptype=value

Page 32: Web Programming Session 15: Django Web Frameworkce.sharif.edu/.../root/Slides/S15-Django-Models.pdf · 2016-05-10 · Web Applications & Databases • In modern Web applications,

Deleting and Updating Objects

Entry.objects.filter( rating=4 ).update(rating=5)

Entry.objects.filter(rating__lte=2).delete()

Page 33: Web Programming Session 15: Django Web Frameworkce.sharif.edu/.../root/Slides/S15-Django-Models.pdf · 2016-05-10 · Web Applications & Databases • In modern Web applications,

Django Admin

• One of the most powerful parts of Django is the automatic admin interface.

• Let's see Django admin for our project!

Page 34: Web Programming Session 15: Django Web Frameworkce.sharif.edu/.../root/Slides/S15-Django-Models.pdf · 2016-05-10 · Web Applications & Databases • In modern Web applications,

Any questions?

Thank you.

�38