Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Lesson 6 - Models and Data Storage

Lesson 6 - Models and Data Storage

Dana Spiegel

October 23, 2012
Tweet

More Decks by Dana Spiegel

Other Decks in Technology

Transcript

  1. Quick Review • Web URLs and ports • The request/response

    cycle • Web frameworks • MVC patterns for web apps • Introduction to Django • Views and templates • Serving a page • Running your web app on the dev server 2
  2. Django Models • Models are the basis of Django’s ORM

    • To define a data model, you create a class that inherits from Django’s Model class • This gives you all of Django’s built in functionality for models • Django models are just python objects with some special features • They can be stored in a database (INSERT and UPDATE) • They can be queried based on their fields (SELECT) • They can be related to each other (ForeignKey) • Each model maps into a database table • Django provides an id field automatically, which maps into the database 3 from django.db import models class Person(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30)
  3. Fields • Django provides a number of useful fields for

    holding information • AutoField • BigIntegerField, DecimalField, FloatField, IntegerField, PositiveIntegerField, PositiveSmallIntegerField, SmallIntegerField • BooleanField • CharField, SlugField, TextField • DateField, DateTimeField, TimeField • FileField, FilePathField, ImageField • EmailField, IPAddressField, GenericIPAddressField, URLField • Important to choose the correct field for the data being stored • Some fields have settings, like max_length, max_digits, editable, blank, and db_index • Fields map into a column in the table that represents the object to which they belong 4 1. https://docs.djangoproject.com/en/1.4/ref/models/fields/#model-field-types
  4. Relationships • Creating relationships between Models is possible, and makes

    use of ForeignKeys and intermediary tables • One-to-One: OneToOneField • One-to-Many: ForeignKeyField • Many-to-Many: ManyToManyField • When defining a relationship, you must specify the name of the related model • A related model can exist in another applications! • Using related_name when defining a ForeignKey or ManyToManyField enables backwards and forwards queries 5 class Car(models.Model): manufacturer = models.ForeignKey('Manufacturer') # ... class Manufacturer(models.Model): # ...
  5. The Django Shell • The interactive Django shell is like

    the python interpreter (it actually is the python interpreter) but with Django built in • Settings are automatically loaded and django libraries are available • Can use defined Models in any configured application • Can execute code as if it were running in your web app • Useful ways to use the Django Shell: • Create model objects • Run ORM queries • Run utility methods • Access and use other installed and configured libraries 6 ./manage.py shell
  6. Creating Model Instances • Models work just like classes •

    They can be instantiated to create object instances and can be used just like other python objects • Each field that’s defined in the model becomes an instance property • Be careful to only assign to a field a python type that is appropriate • If you assign an int to a CharField, it will be an int initially, but will be a unicode string when retrieved from the database • The id field is None until the object is saved to the database • The id field is filled in by the database, since the database provides a central place for generating unique identifiers (for distributed web apps) 7 >>> p = Person() >>> p.first_name = 'Bob' >>> print p.first_name Bob
  7. Setting Up Your Database • Django connects to the database

    automatically, but you must manually create the tables to store the information • This ensures that changing a model doesn’t implicitly change your tables • Important for making changes to your application over time! • Django provides a built in syncdb command that will create your tables for you 8 $ ./manage.py syncdb DEBUG 2012-10-23 04:27:49,417 util 3954 140355547911936 (0.030) SELECT name FROM sqlite_master WHERE type='table' AND NOT name='sqlite_sequence' ORDER BY name; args=() Creating tables ... Creating table project_person DEBUG 2012-10-23 04:30:31,461 util 3978 139709764650752 (0.039) CREATE TABLE "project_person" ( "id" integer NOT NULL PRIMARY KEY, "first_name" varchar(30) NOT NULL, "last_name" varchar(30) NOT NULL )
  8. Generated Tables • When using syncdb django will create tables

    with names of the form <application name>_<model name> • Ex: project_person • This ensures that tables are properly namespaced, so 2 projects with models that have the same name will create different tables in the database • Ex: project_person and project2_person • To see the SQL DDL that Django generates, use ./manage.py sqlall • Django will add all of the configured indexes, including those for the automatically provided id field 9 CREATE TABLE "project_person" ( "id" integer NOT NULL PRIMARY KEY, "first_name" varchar(30) NOT NULL, "last_name" varchar(30) NOT NULL ) ;
  9. Saving Data to the Database • After syncdb, you can

    save objects to the database • You can check that the object is in the project_person table by using sqlite3 • .save() performs an insert or an update automatically 10 In [1]: import project.models In [2]: p=project.models.Person() In [3]: p.first_name = 'John'; In [4]: p.last_name = 'Doe' In [5]: p.save() $ sqlite3 sqlite.db SQLite version 3.7.9 2011-11-01 00:52:41 Enter ".help" for instructions Enter SQL statements terminated with a ";" sqlite> select * from project_person; 1|John|Doe
  10. Querying the Database • Querying uses Managers • Managers are

    classes that enable queries to be made for models • Each model will have its own Manager, available through the model’s objects property • Person.objects • Managers return QuerySets • Using the Manager you can get any object of the model’s type by using get • Get will return a single object only • It will raise an exception if more than one object exists that matches the query 11 import project.models p = project.models.Person.objects.get(first_name='John') print p.id 1 print p.last_name Doe
  11. Querying the Database (cont’d.) • To get all of the

    objects that match a query, use filter • Even if there’s only one object, filter will return a list • The returned list will be in database order (usually ordered by id) • To return in a different order, use order_by 12 import project.models people = project.models.Person.objects.filter(last_name='Doe') print people [<Person: Person object>, <Person: Person object>, <Person: Person object>] print people[0].first_name John from project.models import Person people = Person.objects.filter(last_name='Doe').order_by('first_name') print people[0].first_name Jane
  12. Using Related Models • To assign a related object, just

    set the object property or add the object to the collection • When saving an object with a relationship, you must save the dependent object first 13 >>> p = Person(first_name='John', last_name='Doe') >>> a1 = Address(street_address_1='123 Main Street', city='New York', state_province='NY', postal_code='10003', country='us') >>> a1.person = p >>> p.addresses.add(a1) ... IntegrityError: project_address.person_id may not be NULL >>> p.addresses.add(a1) DEBUG 2012-10-23 05:30:29,305 util 4130 140657423681280 (0.000) INSERT INTO "project_address" ("person_id", "street_address_1", "street_address_2", "city", "state_province", "postal_code", "country") VALUES (1, 123 Main Street, , New York, NY, 10003, us); args=[1, '123 Main Street', '', 'New York', 'NY', '10003', 'us']
  13. Using Related Models (cont’d.) • To access a related field,

    you can use object property directly for OneToOneFields • For ManyToManyFields or ForeignKeys, you must query the RelatedManager 14 >>> p.addresses <django.db.models.fields.related.RelatedManager at 0x3ae9710> >>> p.addresses.all() [<Address: Address object>] >>> p.addresses.all()[0].street_address_1 u'123 Main Street'
  14. In Class: Using models • Create models for a parking

    lot, as we did last week • Add project to Github • Homework: • Read https://docs.djangoproject.com/en/1.4/ref/models/fields/ #foreignkey • Finish creating the models • Check in your finished files to Github • Email me when you are done 16