MIT Global Startup Labs México 2013

Similar documents
Accelerating Information Technology Innovation

Accelerating Information Technology Innovation

CE419 Web Programming. Session 15: Django Web Framework

Accelerating Information Technology Innovation

Webdev: Building Django Apps. Ryan Fox Andrew Glassman MKE Python

CSV Importer Documentation

staff Documentation Release 1.2

django-model-utils Documentation

DDF Documentation. Release Paulo Cheque

widgets, events, layout loosely similar to Swing test browser, or plugin for testing with real browser on local system

django-audit-log Documentation

Django Admin Sortable Documentation

django-modeltranslation Documentation

Relational Model. IT 5101 Introduction to Database Systems. J.G. Zheng Fall 2011

정재성

generates scaffolding/framework for models, views

canary Documentation Release 0.1 Branton K. Davis

Runtime Dynamic Models Documentation Release 1.0

South Documentation. Release 1.0. Andrew Godwin

Introduction to pysqlite

django-scaffold Documentation

The Definitive Guide to Django

xmodels Documentation

Tomasz Szumlak WFiIS AGH 23/10/2017, Kraków

Information Systems Engineering. SQL Structured Query Language DDL Data Definition (sub)language

Moving to a Sustainable Web Development Environment for Library Web Applications

Flask-MongoEngine Documentation

CS 2316 Exam 4 Fall 2011

EE221 Databases Practicals Manual

L6 Application Programming. Thibault Sellam Fall 2018

CSCI-UA: Database Design & Web Implementation. Professor Evan Sandhaus Lecture #23: SQLite

SQL Data Definition Language: Create and Change the Database Ray Lockwood

django-filter Documentation

CS108 Lecture 19: The Python DBAPI

3344 Database Lab. 1. Overview. 2. Lab Requirements. In this lab, you will:

Constraints. Primary Key Foreign Key General table constraints Domain constraints Assertions Triggers. John Edgar 2

Django File Picker Documentation

Carnegie Mellon Univ. Dept. of Computer Science /615 - DB Applications. Today's Party. Example Database. Faloutsos/Pavlo CMU /615

7401ICT eservice Technology. (Some of) the actual examination questions will be more precise than these.

MIT AITI Python Software Development Lab DJ1:

EGCI 321: Database Systems. Dr. Tanasanee Phienthrakul

Lecture 10(-ish) Web [Application] Frameworks

django-filter Documentation

Product: DQ Order Manager Release Notes

Schema Migrations Table Does Not Exist Yet

Advance Application of DJANGO Integrated With TASTYPIE API Framework for the Software Development

Private Institute of Aga NETWORK DATABASE LECTURER NIYAZ M. SALIH

Reminders. Full Django products are due next Thursday! CS370, Günay (Emory) Spring / 6

Django starting guide

Django Extras Documentation

Access Intermediate

Access Intermediate

TYPES OF VARIABLES, STRUCTURE OF DATASETS, AND BASIC STATA LAYOUT

INFO 1103 Homework Project 2

T-SQL Training: T-SQL for SQL Server for Developers

CS W Introduction to Databases Spring Computer Science Department Columbia University

Database Management Systems,

django-generic-aggregation Documentation

Tablo Documentation. Release Conservation Biology Institute

DATABASE SYSTEMS. Database programming in a web environment. Database System Course,

The URL of the whole system is:

Django design patterns Documentation

CT 229 Fundamentals of Java Syntax

Relational Data Mapping with GORM. Fall Forecast 2009

CS 2316 Exam 2 Practice ANSWER KEY

Simple sets of data can be expressed in a simple table, much like a

Ninja Typers Web Application Design Document By Marvin Farrell C

Accelerating Information Technology Innovation

django-model-report Documentation

Vittles Documentation

Database Programming with SQL

User Guide. Product Design. Version 2.2.2

4.6.5 Data Sync User Manual.

Intro. Scheme Basics. scm> 5 5. scm>

Gmail: , find, and manage your contacts

3 The Building Blocks: Data Types, Literals, and Variables

Django ORM crash

the employee s next birthday is in the past. This mechanism will consistently update the employee s next birthday.

Django Synctool Documentation

django-image-cropping Documentation

Sertifi Text Tags Creating Form Fields and Merge Fields for Word Documents

django-gollum Documentation

Oracle Database 10g Express

Microsoft Access - Using Relational Database Data Queries (Stored Procedures) Paul A. Harris, Ph.D. Director, GCRC Informatics.

You can use Dreamweaver to build master and detail Web pages, which

Using C++, design an Abstract Data Type class named MyGrades. The class must have the following private members :

Relational databases and SQL

Puzzlehunt Server Documentation

CS 2316 Homework 9a GT Room Reservation Login

SQL Constraints and Triggers

MongoDB An Overview. 21-Oct Socrates

CS 4320/5320 Homework 2

Ecocion Facility Management System Alex Anderson Niles Hacking Ryan Shipp June 16, 2015

DATABASE SYSTEMS. Database programming in a web environment. Database System Course, 2016

Checklist for Testing of Web Application

Database Programming with PL/SQL

SQL Fundamentals. Chapter 3. Class 03: SQL Fundamentals 1

silk Documentation Release 0.3 Michael Ford

django_podcasting Documentation

T H E I N T E R A C T I V E S H E L L

Transcription:

MIT Global Startup Labs México 2013 http://aiti.mit.edu Lesson 2 Django Models

What is a model? A class describing data in your application Basically, a class with attributes for each data field that you care about The schema for your data A diagrammatic presentation 2

Why use Django models Avoid direct work with the database No need to handle database connections, timeouts, etc. Let Django do it for you. Class that extends models.model 3

Django fields All you do is define a field type Ex: active = models.booleanfield() Django handles the rest: Bit value in sql database Represented as a checkbox on a webpage Validation of values 4

Before Models: from django.shortcuts import render_to_response import MySQLdb def book_list(request): db = MySQLdb.connect(user='me', db='mydb', (' host='localhost passwd='secret', () db.cursor cursor = (' name cursor.execute('select name FROM books ORDER BY names = [row[0] for row in cursor.fetchall()] () db.close ({ names return render_to_response('book_list.html', {'names':

After Models: from django.shortcuts import render_to_response from mysite.books.models import Book def book_list(request): (' Book.objects.order_by('name books = ({ books return render_to_response('book_list.html', {'books':

Django Model Syntax class Musician(models.Model): first_name = models.charfield(max_length=50) last_name = models.charfield(max_length=50) instrument = models.charfield(max_length=100) def unicode (): return last_name+, +first_name class Album(models.Model): artist = models.foreignkey(musician) name = models.charfield(max_length=100) release_date = models.datefield() num_stars = models.integerfield() def unicode (): return name 7

Important Django field types BooleanField Checkbox CharField(max_length) Single-line textbox DateField Javascript calendar DateTimeField Javascript calendar, time picker 8

Important Django field types DecimalField(max_digits, decimal_places) Decimal numbers EmailField Charfield that validates email address FileField File upload, stores path in database FloatField Floating point numbers 9

Important Django field types ImageField ***Don t use Stores images IntegerField Integer textbox PositiveIntegerField Integer textbox for positive integers TextField Multi-line textbox 10

Important Django field types TimeField Time picker URLField Textbox for URLs Anything you create 11

Django Relationship Fields ForeignKey(foreign class) Many-to-one ManyToManyField(foreign class) Uses a temporary table to join tables together OneToOneField(foreign class) Enforces uniqueness (i.e. foreign key with unique=true) 12

Field options null: if True, empty fields will be stored as NULL in database. blank: if True, field is allowed to be blank. default is False. choices: List or tuple of 2-tuples to use as field choices Django will represent it with a drop-down instead of a textbox class Foo(models.Model): GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female'), ( NS, Not specified ) ) gender = models.charfield(max_length=2, choices=gender_choices) 13

More Field Options default: default value for a field primary_key: if True, this field is the primary key for the model unique: if True, this will have to be unique throughout the table verbose_field_name: provides a human readable file name 14

DateField and DateTimeField auto_now options Any time the object is saved, the field will be updated with the current time. auto_now_add The time will always be equal to the creation date of the object. 15

Model Methods unicode (): Equivilant of tostring used for autogenerated admin pages get_absolute_url() Used for deciding URLs that reference a specific object 16

Django Model Syntax (example) class Musician(models.Model): first_name = models.charfield(max_length=50) last_name = models.charfield(max_length=50) instrument = models.charfield(max_length=100) def unicode (): return last_name+, +first_name class Album(models.Model): artist = models.foreignkey(musician) name = models.charfield(max_length=100) release_date = models.datefield() num_stars = models.integerfield() def unicode (): return name 17

Creating Models Manually >>> from music.models import Musician >>> m1 = Musician(first_name='Jimi', last_name='hendrix', (' instrument='guitar () m1.save <<< >>> m2 = Musician(first_name="Eric", last_name= Clapton, (' instrument='guitar () m2.save <<< () Musician.objects.all >>> Musician_list = >>> Musician_list [<Musician: Hendrix, Jimi>, <Musician: Clapton, Eric>] #remember the unicode!! 18

Filtering ( Musician.objects.filter(first_name= Jimi <<< [<Musician: Hendrix, Jimi>] ( Musician.objects.filter(instrument= guitar <<< [<Musician: Hendrix, Jimi>, <Musician: Clapton, Eric>] #returns a QuerySet, not an individual Model Object ( Musician.objects.filter(last_name contains= Clap <<< [<Musician: Clapton, Eric>] #double underscore!! 19

Getting ( Musician.objects.get(first_name= Jimi <<< <Musician: Hendrix, Jimi> #returns single object ( Musician.objects.get(instrument= violin <<< Error! DoesNotExist ( Musician.objects.get(instrument= guitar <<< Error! MultipleObjectsReturned #use try/except when using get. 20

Ordering ( Musician.objects.order_by(-last_name <<< [<Musician: Hendrix, Jimi>, <Musician: Clapton, Eric>] Easier way: add class Meta to Model class class Musician(models.Model): first_name = models.charfield(max_length=50) last_name = models.charfield(max_length=50) instrument = models.charfield(max_length=100) def unicode (): return last_name+, +first_name class Meta: ordering = [-last_name] 21

More Functionality >>>m1.instrument= drums >>>m1.save() #updates ALL rows, could lead to race condition ( Musicians.objects.filter(id=12).update(instrument= bass <<< #updates only instrument row Chaining >>>Musicians.objects.filter(instrument="guitar").order_by("- (" last_name [<Musician: Hendrix, Jimi>, <Musician: Clapton, Eric>] 22

Rules of Django Models 1. When you update a model, ALWAYS RUN python manage.py syncdb 2. All classes extend models.model 3. Models only live in Apps 4. Django doesn't save objects until you call save() method (...) Album >>>a1 = # a1 is not saved to the database yet! () a1.save <<< # Now it is saved. 23

Tips for Django Models 1. Keep code clean 2. Always create a unicode () method 3. Name your variables well 4. Don t think too much about the database 24