Models
Magnificent Models
Models store data for your app
Key for making dynamic websites!
Models are implemented as Python classes, in
models.py file
Awesome feature of Django: the “object relational
mapper”
Allows you to access/change a database (ex.,
MySQL) just by calling functions on your models
Magnificent Models
Example models:
from django.db import models
class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice = models.CharField(max_length=200)
votes = models.IntegerField()
Magnificent Models
Can easily create instances of your model:
p = Poll(question="What's up?",
pub_date=datetime.datetime.now())
Save it to the database:
p.save()
The object relational mapper takes care of all
the MySQL for you!
Magnificent Models
The object relational mapper even automagically
sets up your MySQL database
Example generated code:
BEGIN;
CREATE TABLE "polls_poll" (
"id" serial NOT NULL PRIMARY KEY,
"question" varchar(200) NOT NULL,
"pub_date" timestamp with time zone NOT NULL
);
CREATE TABLE "polls_choice" (
"id" serial NOT NULL PRIMARY KEY,
"poll_id" integer NOT NULL REFERENCES "polls_poll" ("id"),
"choice" varchar(200) NOT NULL,
"votes" integer NOT NULL
);
COMMIT;
|