tutorial01.txt 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699
  1. =====================================
  2. Writing your first Django app, part 1
  3. =====================================
  4. Let's learn by example.
  5. Throughout this tutorial, we'll walk you through the creation of a basic
  6. poll application.
  7. It'll consist of two parts:
  8. * A public site that lets people view polls and vote in them.
  9. * An admin site that lets you add, change and delete polls.
  10. We'll assume you have :doc:`Django installed </intro/install>` already. You can
  11. tell Django is installed by running the Python interactive interpreter and
  12. typing ``import django``. If that command runs successfully, with no errors,
  13. Django is installed.
  14. .. admonition:: Where to get help:
  15. If you're having trouble going through this tutorial, please post a message
  16. to `django-users`__ or drop by `#django on irc.freenode.net`__ to chat
  17. with other Django users who might be able to help.
  18. __ http://groups.google.com/group/django-users
  19. __ irc://irc.freenode.net/django
  20. Creating a project
  21. ==================
  22. If this is your first time using Django, you'll have to take care of some
  23. initial setup. Namely, you'll need to auto-generate some code that establishes a
  24. Django :term:`project` -- a collection of settings for an instance of Django,
  25. including database configuration, Django-specific options and
  26. application-specific settings.
  27. From the command line, ``cd`` into a directory where you'd like to store your
  28. code, then run the command ``django-admin.py startproject mysite``. This will
  29. create a ``mysite`` directory in your current directory.
  30. .. admonition:: Mac OS X permissions
  31. If you're using Mac OS X, you may see the message "permission denied" when
  32. you try to run ``django-admin.py startproject``. This is because, on
  33. Unix-based systems like OS X, a file must be marked as "executable" before it
  34. can be run as a program. To do this, open Terminal.app and navigate (using
  35. the ``cd`` command) to the directory where :doc:`django-admin.py
  36. </ref/django-admin>` is installed, then run the command
  37. ``chmod +x django-admin.py``.
  38. .. note::
  39. You'll need to avoid naming projects after built-in Python or Django
  40. components. In particular, this means you should avoid using names like
  41. ``django`` (which will conflict with Django itself) or ``test`` (which
  42. conflicts with a built-in Python package).
  43. :doc:`django-admin.py </ref/django-admin>` should be on your system path if you
  44. installed Django via ``python setup.py``. If it's not on your path, you can find
  45. it in ``site-packages/django/bin``, where ```site-packages``` is a directory
  46. within your Python installation. Consider symlinking to :doc:`django-admin.py
  47. </ref/django-admin>` from some place on your path, such as
  48. :file:`/usr/local/bin`.
  49. .. admonition:: Where should this code live?
  50. If your background is in PHP, you're probably used to putting code under the
  51. Web server's document root (in a place such as ``/var/www``). With Django,
  52. you don't do that. It's not a good idea to put any of this Python code
  53. within your Web server's document root, because it risks the possibility
  54. that people may be able to view your code over the Web. That's not good for
  55. security.
  56. Put your code in some directory **outside** of the document root, such as
  57. :file:`/home/mycode`.
  58. Let's look at what :djadmin:`startproject` created::
  59. mysite/
  60. __init__.py
  61. manage.py
  62. settings.py
  63. urls.py
  64. These files are:
  65. * :file:`__init__.py`: An empty file that tells Python that this directory
  66. should be considered a Python package. (Read `more about packages`_ in the
  67. official Python docs if you're a Python beginner.)
  68. * :file:`manage.py`: A command-line utility that lets you interact with this
  69. Django project in various ways. You can read all the details about
  70. :file:`manage.py` in :doc:`/ref/django-admin`.
  71. * :file:`settings.py`: Settings/configuration for this Django project.
  72. :doc:`/topics/settings` will tell you all about how settings work.
  73. * :file:`urls.py`: The URL declarations for this Django project; a "table of
  74. contents" of your Django-powered site. You can read more about URLs in
  75. :doc:`/topics/http/urls`.
  76. .. _more about packages: http://docs.python.org/tutorial/modules.html#packages
  77. The development server
  78. ----------------------
  79. Let's verify this worked. Change into the :file:`mysite` directory, if you
  80. haven't already, and run the command ``python manage.py runserver``. You'll see
  81. the following output on the command line::
  82. Validating models...
  83. 0 errors found.
  84. Django version 1.0, using settings 'mysite.settings'
  85. Development server is running at http://127.0.0.1:8000/
  86. Quit the server with CONTROL-C.
  87. You've started the Django development server, a lightweight Web server written
  88. purely in Python. We've included this with Django so you can develop things
  89. rapidly, without having to deal with configuring a production server -- such as
  90. Apache -- until you're ready for production.
  91. Now's a good time to note: DON'T use this server in anything resembling a
  92. production environment. It's intended only for use while developing. (We're in
  93. the business of making Web frameworks, not Web servers.)
  94. Now that the server's running, visit http://127.0.0.1:8000/ with your Web
  95. browser. You'll see a "Welcome to Django" page, in pleasant, light-blue pastel.
  96. It worked!
  97. .. admonition:: Changing the port
  98. By default, the :djadmin:`runserver` command starts the development server
  99. on the internal IP at port 8000.
  100. If you want to change the server's port, pass
  101. it as a command-line argument. For instance, this command starts the server
  102. on port 8080:
  103. .. code-block:: bash
  104. python manage.py runserver 8080
  105. If you want to change the server's IP, pass it along with the port. So to
  106. listen on all public IPs (useful if you want to show off your work on other
  107. computers), use:
  108. .. code-block:: bash
  109. python manage.py runserver 0.0.0.0:8000
  110. Full docs for the development server can be found in the
  111. :djadmin:`runserver` reference.
  112. Database setup
  113. --------------
  114. Now, edit :file:`settings.py`. It's a normal Python module with
  115. module-level variables representing Django settings. Change the
  116. following keys in the :setting:`DATABASES` ``'default'`` item to match
  117. your databases connection settings.
  118. * :setting:`ENGINE` -- Either
  119. ``'django.db.backends.postgresql_psycopg2'``,
  120. ``'django.db.backends.mysql'`` or
  121. ``'django.db.backends.sqlite3'``. Other backends are
  122. :setting:`also available <ENGINE>`.
  123. * :setting:`NAME` -- The name of your database. If you're using
  124. SQLite, the database will be a file on your computer; in that
  125. case, :setting:`NAME` should be the full absolute path,
  126. including filename, of that file. If the file doesn't exist, it
  127. will automatically be created when you synchronize the database
  128. for the first time (see below).
  129. When specifying the path, always use forward slashes, even on
  130. Windows (e.g. ``C:/homes/user/mysite/sqlite3.db``).
  131. * :setting:`USER` -- Your database username (not used for SQLite).
  132. * :setting:`PASSWORD` -- Your database password (not used for
  133. SQLite).
  134. * :setting:`HOST` -- The host your database is on. Leave this as
  135. an empty string if your database server is on the same physical
  136. machine (not used for SQLite).
  137. If you're new to databases, we recommend simply using SQLite (by
  138. setting :setting:`ENGINE` to ``'django.db.backends.sqlite3'``). SQLite
  139. is included as part of Python 2.5 and later, so you won't need to
  140. install anything else.
  141. .. note::
  142. If you're using PostgreSQL or MySQL, make sure you've created a database by
  143. this point. Do that with "``CREATE DATABASE database_name;``" within your
  144. database's interactive prompt.
  145. If you're using SQLite, you don't need to create anything beforehand - the
  146. database file will be created automatically when it is needed.
  147. While you're editing :file:`settings.py`, take note of the
  148. :setting:`INSTALLED_APPS` setting towards the bottom of the file. That variable
  149. holds the names of all Django applications that are activated in this Django
  150. instance. Apps can be used in multiple projects, and you can package and
  151. distribute them for use by others in their projects.
  152. By default, :setting:`INSTALLED_APPS` contains the following apps, all of which
  153. come with Django:
  154. * :mod:`django.contrib.auth` -- An authentication system.
  155. * :mod:`django.contrib.contenttypes` -- A framework for content types.
  156. * :mod:`django.contrib.sessions` -- A session framework.
  157. * :mod:`django.contrib.sites` -- A framework for managing multiple sites
  158. with one Django installation.
  159. These applications are included by default as a convenience for the common case.
  160. Each of these applications makes use of at least one database table, though,
  161. so we need to create the tables in the database before we can use them. To do
  162. that, run the following command:
  163. .. code-block:: bash
  164. python manage.py syncdb
  165. The :djadmin:`syncdb` command looks at the :setting:`INSTALLED_APPS` setting and
  166. creates any necessary database tables according to the database settings in your
  167. :file:`settings.py` file. You'll see a message for each database table it
  168. creates, and you'll get a prompt asking you if you'd like to create a superuser
  169. account for the authentication system. Go ahead and do that.
  170. If you're interested, run the command-line client for your database and type
  171. ``\dt`` (PostgreSQL), ``SHOW TABLES;`` (MySQL), or ``.schema`` (SQLite) to
  172. display the tables Django created.
  173. .. admonition:: For the minimalists
  174. Like we said above, the default applications are included for the common
  175. case, but not everybody needs them. If you don't need any or all of them,
  176. feel free to comment-out or delete the appropriate line(s) from
  177. :setting:`INSTALLED_APPS` before running :djadmin:`syncdb`. The
  178. :djadmin:`syncdb` command will only create tables for apps in
  179. :setting:`INSTALLED_APPS`.
  180. .. _creating-models:
  181. Creating models
  182. ===============
  183. Now that your environment -- a "project" -- is set up, you're set to start
  184. doing work.
  185. Each application you write in Django consists of a Python package, somewhere
  186. on your `Python path`_, that follows a certain convention. Django comes with a
  187. utility that automatically generates the basic directory structure of an app,
  188. so you can focus on writing code rather than creating directories.
  189. .. admonition:: Projects vs. apps
  190. What's the difference between a project and an app? An app is a Web
  191. application that does something -- e.g., a weblog system, a database of
  192. public records or a simple poll app. A project is a collection of
  193. configuration and apps for a particular Web site. A project can contain
  194. multiple apps. An app can be in multiple projects.
  195. In this tutorial, we'll create our poll app in the :file:`mysite` directory,
  196. for simplicity. As a consequence, the app will be coupled to the project --
  197. that is, Python code within the poll app will refer to ``mysite.polls``.
  198. Later in this tutorial, we'll discuss decoupling your apps for distribution.
  199. To create your app, make sure you're in the :file:`mysite` directory and type
  200. this command:
  201. .. code-block:: bash
  202. python manage.py startapp polls
  203. That'll create a directory :file:`polls`, which is laid out like this::
  204. polls/
  205. __init__.py
  206. models.py
  207. tests.py
  208. views.py
  209. This directory structure will house the poll application.
  210. The first step in writing a database Web app in Django is to define your models
  211. -- essentially, your database layout, with additional metadata.
  212. .. admonition:: Philosophy
  213. A model is the single, definitive source of data about your data. It contains
  214. the essential fields and behaviors of the data you're storing. Django follows
  215. the :ref:`DRY Principle <dry>`. The goal is to define your data model in one
  216. place and automatically derive things from it.
  217. In our simple poll app, we'll create two models: polls and choices. A poll has
  218. a question and a publication date. A choice has two fields: the text of the
  219. choice and a vote tally. Each choice is associated with a poll.
  220. These concepts are represented by simple Python classes. Edit the
  221. :file:`polls/models.py` file so it looks like this::
  222. from django.db import models
  223. class Poll(models.Model):
  224. question = models.CharField(max_length=200)
  225. pub_date = models.DateTimeField('date published')
  226. class Choice(models.Model):
  227. poll = models.ForeignKey(Poll)
  228. choice = models.CharField(max_length=200)
  229. votes = models.IntegerField()
  230. The code is straightforward. Each model is represented by a class that
  231. subclasses :class:`django.db.models.Model`. Each model has a number of class
  232. variables, each of which represents a database field in the model.
  233. Each field is represented by an instance of a :class:`~django.db.models.Field`
  234. class -- e.g., :class:`~django.db.models.CharField` for character fields and
  235. :class:`~django.db.models.DateTimeField` for datetimes. This tells Django what
  236. type of data each field holds.
  237. The name of each :class:`~django.db.models.Field` instance (e.g. ``question`` or
  238. ``pub_date`` ) is the field's name, in machine-friendly format. You'll use this
  239. value in your Python code, and your database will use it as the column name.
  240. You can use an optional first positional argument to a
  241. :class:`~django.db.models.Field` to designate a human-readable name. That's used
  242. in a couple of introspective parts of Django, and it doubles as documentation.
  243. If this field isn't provided, Django will use the machine-readable name. In this
  244. example, we've only defined a human-readable name for ``Poll.pub_date``. For all
  245. other fields in this model, the field's machine-readable name will suffice as
  246. its human-readable name.
  247. Some :class:`~django.db.models.Field` classes have required elements.
  248. :class:`~django.db.models.CharField`, for example, requires that you give it a
  249. :attr:`~django.db.models.Field.max_length`. That's used not only in the database
  250. schema, but in validation, as we'll soon see.
  251. Finally, note a relationship is defined, using
  252. :class:`~django.db.models.ForeignKey`. That tells Django each Choice is related
  253. to a single Poll. Django supports all the common database relationships:
  254. many-to-ones, many-to-manys and one-to-ones.
  255. .. _`Python path`: http://docs.python.org/tutorial/modules.html#the-module-search-path
  256. Activating models
  257. =================
  258. That small bit of model code gives Django a lot of information. With it, Django
  259. is able to:
  260. * Create a database schema (``CREATE TABLE`` statements) for this app.
  261. * Create a Python database-access API for accessing Poll and Choice objects.
  262. But first we need to tell our project that the ``polls`` app is installed.
  263. .. admonition:: Philosophy
  264. Django apps are "pluggable": You can use an app in multiple projects, and
  265. you can distribute apps, because they don't have to be tied to a given
  266. Django installation.
  267. Edit the :file:`settings.py` file again, and change the
  268. :setting:`INSTALLED_APPS` setting to include the string ``'mysite.polls'``. So
  269. it'll look like this::
  270. INSTALLED_APPS = (
  271. 'django.contrib.auth',
  272. 'django.contrib.contenttypes',
  273. 'django.contrib.sessions',
  274. 'django.contrib.sites',
  275. 'mysite.polls'
  276. )
  277. Now Django knows ``mysite`` includes the ``polls`` app. Let's run another
  278. command:
  279. .. code-block:: bash
  280. python manage.py sql polls
  281. You should see something similar to the following (the ``CREATE TABLE`` SQL
  282. statements for the polls app):
  283. .. code-block:: sql
  284. BEGIN;
  285. CREATE TABLE "polls_poll" (
  286. "id" serial NOT NULL PRIMARY KEY,
  287. "question" varchar(200) NOT NULL,
  288. "pub_date" timestamp with time zone NOT NULL
  289. );
  290. CREATE TABLE "polls_choice" (
  291. "id" serial NOT NULL PRIMARY KEY,
  292. "poll_id" integer NOT NULL REFERENCES "polls_poll" ("id"),
  293. "choice" varchar(200) NOT NULL,
  294. "votes" integer NOT NULL
  295. );
  296. COMMIT;
  297. Note the following:
  298. * The exact output will vary depending on the database you are using.
  299. * Table names are automatically generated by combining the name of the app
  300. (``polls``) and the lowercase name of the model -- ``poll`` and
  301. ``choice``. (You can override this behavior.)
  302. * Primary keys (IDs) are added automatically. (You can override this, too.)
  303. * By convention, Django appends ``"_id"`` to the foreign key field name.
  304. Yes, you can override this, as well.
  305. * The foreign key relationship is made explicit by a ``REFERENCES``
  306. statement.
  307. * It's tailored to the database you're using, so database-specific field
  308. types such as ``auto_increment`` (MySQL), ``serial`` (PostgreSQL), or
  309. ``integer primary key`` (SQLite) are handled for you automatically. Same
  310. goes for quoting of field names -- e.g., using double quotes or single
  311. quotes. The author of this tutorial runs PostgreSQL, so the example
  312. output is in PostgreSQL syntax.
  313. * The :djadmin:`sql` command doesn't actually run the SQL in your database -
  314. it just prints it to the screen so that you can see what SQL Django thinks
  315. is required. If you wanted to, you could copy and paste this SQL into your
  316. database prompt. However, as we will see shortly, Django provides an
  317. easier way of committing the SQL to the database.
  318. If you're interested, also run the following commands:
  319. * :djadmin:`python manage.py validate <validate>` -- Checks for any errors
  320. in the construction of your models.
  321. * :djadmin:`python manage.py sqlcustom polls <sqlcustom>` -- Outputs any
  322. :ref:`custom SQL statements <initial-sql>` (such as table modifications or
  323. constraints) that are defined for the application.
  324. * :djadmin:`python manage.py sqlclear polls <sqlclear>` -- Outputs the
  325. necessary ``DROP TABLE`` statements for this app, according to which
  326. tables already exist in your database (if any).
  327. * :djadmin:`python manage.py sqlindexes polls <sqlindexes>` -- Outputs the
  328. ``CREATE INDEX`` statements for this app.
  329. * :djadmin:`python manage.py sqlall polls <sqlall>` -- A combination of all
  330. the SQL from the :djadmin:`sql`, :djadmin:`sqlcustom`, and
  331. :djadmin:`sqlindexes` commands.
  332. Looking at the output of those commands can help you understand what's actually
  333. happening under the hood.
  334. Now, run :djadmin:`syncdb` again to create those model tables in your database:
  335. .. code-block:: bash
  336. python manage.py syncdb
  337. The :djadmin:`syncdb` command runs the sql from 'sqlall' on your database for
  338. all apps in :setting:`INSTALLED_APPS` that don't already exist in your database.
  339. This creates all the tables, initial data and indexes for any apps you have
  340. added to your project since the last time you ran syncdb. :djadmin:`syncdb` can
  341. be called as often as you like, and it will only ever create the tables that
  342. don't exist.
  343. Read the :doc:`django-admin.py documentation </ref/django-admin>` for full
  344. information on what the ``manage.py`` utility can do.
  345. Playing with the API
  346. ====================
  347. Now, let's hop into the interactive Python shell and play around with the free
  348. API Django gives you. To invoke the Python shell, use this command:
  349. .. code-block:: bash
  350. python manage.py shell
  351. We're using this instead of simply typing "python", because ``manage.py`` sets
  352. up the project's environment for you. "Setting up the environment" involves two
  353. things:
  354. * Putting ``mysite`` on ``sys.path``. For flexibility, several pieces of
  355. Django refer to projects in Python dotted-path notation (e.g.
  356. ``'mysite.polls.models'``). In order for this to work, the ``mysite``
  357. package has to be on ``sys.path``.
  358. We've already seen one example of this: the :setting:`INSTALLED_APPS`
  359. setting is a list of packages in dotted-path notation.
  360. * Setting the ``DJANGO_SETTINGS_MODULE`` environment variable, which gives
  361. Django the path to your ``settings.py`` file.
  362. .. admonition:: Bypassing manage.py
  363. If you'd rather not use ``manage.py``, no problem. Just make sure ``mysite``
  364. is at the root level on the Python path (i.e., ``import mysite`` works) and
  365. set the ``DJANGO_SETTINGS_MODULE`` environment variable to
  366. ``mysite.settings``.
  367. For more information on all of this, see the :doc:`django-admin.py
  368. documentation </ref/django-admin>`.
  369. Once you're in the shell, explore the :doc:`database API </topics/db/queries>`::
  370. >>> from mysite.polls.models import Poll, Choice # Import the model classes we just wrote.
  371. # No polls are in the system yet.
  372. >>> Poll.objects.all()
  373. []
  374. # Create a new Poll.
  375. >>> import datetime
  376. >>> p = Poll(question="What's up?", pub_date=datetime.datetime.now())
  377. # Save the object into the database. You have to call save() explicitly.
  378. >>> p.save()
  379. # Now it has an ID. Note that this might say "1L" instead of "1", depending
  380. # on which database you're using. That's no biggie; it just means your
  381. # database backend prefers to return integers as Python long integer
  382. # objects.
  383. >>> p.id
  384. 1
  385. # Access database columns via Python attributes.
  386. >>> p.question
  387. "What's up?"
  388. >>> p.pub_date
  389. datetime.datetime(2007, 7, 15, 12, 00, 53)
  390. # Change values by changing the attributes, then calling save().
  391. >>> p.pub_date = datetime.datetime(2007, 4, 1, 0, 0)
  392. >>> p.save()
  393. # objects.all() displays all the polls in the database.
  394. >>> Poll.objects.all()
  395. [<Poll: Poll object>]
  396. Wait a minute. ``<Poll: Poll object>`` is, utterly, an unhelpful representation
  397. of this object. Let's fix that by editing the polls model (in the
  398. ``polls/models.py`` file) and adding a
  399. :meth:`~django.db.models.Model.__unicode__` method to both ``Poll`` and
  400. ``Choice``::
  401. class Poll(models.Model):
  402. # ...
  403. def __unicode__(self):
  404. return self.question
  405. class Choice(models.Model):
  406. # ...
  407. def __unicode__(self):
  408. return self.choice
  409. .. admonition:: If :meth:`~django.db.models.Model.__unicode__` doesn't seem to work
  410. If you add the :meth:`~django.db.models.Model.__unicode__` method to your
  411. models and don't see any change in how they're represented, you're most
  412. likely using an old version of Django. (This version of the tutorial is
  413. written for the latest development version of Django.) If you're using a
  414. Subversion checkout of Django's development version (see :doc:`the
  415. installation docs </topics/install>` for more information), you shouldn't have
  416. any problems.
  417. If you want to stick with an older version of Django, you'll want to switch
  418. to `the Django 0.96 tutorial`_, because this tutorial covers several features
  419. that only exist in the Django development version.
  420. .. _the Django 0.96 tutorial: http://www.djangoproject.com/documentation/0.96/tutorial01/
  421. It's important to add :meth:`~django.db.models.Model.__unicode__` methods to
  422. your models, not only for your own sanity when dealing with the interactive
  423. prompt, but also because objects' representations are used throughout Django's
  424. automatically-generated admin.
  425. .. admonition:: Why :meth:`~django.db.models.Model.__unicode__` and not
  426. :meth:`~django.db.models.Model.__str__`?
  427. If you're familiar with Python, you might be in the habit of adding
  428. :meth:`~django.db.models.Model.__str__` methods to your classes, not
  429. :meth:`~django.db.models.Model.__unicode__` methods. We use
  430. :meth:`~django.db.models.Model.__unicode__` here because Django models deal
  431. with Unicode by default. All data stored in your database is converted to
  432. Unicode when it's returned.
  433. Django models have a default :meth:`~django.db.models.Model.__str__` method
  434. that calls :meth:`~django.db.models.Model.__unicode__` and converts the
  435. result to a UTF-8 bytestring. This means that ``unicode(p)`` will return a
  436. Unicode string, and ``str(p)`` will return a normal string, with characters
  437. encoded as UTF-8.
  438. If all of this is jibberish to you, just remember to add
  439. :meth:`~django.db.models.Model.__unicode__` methods to your models. With any
  440. luck, things should Just Work for you.
  441. Note these are normal Python methods. Let's add a custom method, just for
  442. demonstration::
  443. import datetime
  444. # ...
  445. class Poll(models.Model):
  446. # ...
  447. def was_published_today(self):
  448. return self.pub_date.date() == datetime.date.today()
  449. Note the addition of ``import datetime`` to reference Python's standard
  450. ``datetime`` module.
  451. Save these changes and start a new Python interactive shell by running
  452. ``python manage.py shell`` again::
  453. >>> from mysite.polls.models import Poll, Choice
  454. # Make sure our __unicode__() addition worked.
  455. >>> Poll.objects.all()
  456. [<Poll: What's up?>]
  457. # Django provides a rich database lookup API that's entirely driven by
  458. # keyword arguments.
  459. >>> Poll.objects.filter(id=1)
  460. [<Poll: What's up?>]
  461. >>> Poll.objects.filter(question__startswith='What')
  462. [<Poll: What's up?>]
  463. # Get the poll whose year is 2007.
  464. >>> Poll.objects.get(pub_date__year=2007)
  465. <Poll: What's up?>
  466. >>> Poll.objects.get(id=2)
  467. Traceback (most recent call last):
  468. ...
  469. DoesNotExist: Poll matching query does not exist.
  470. # Lookup by a primary key is the most common case, so Django provides a
  471. # shortcut for primary-key exact lookups.
  472. # The following is identical to Poll.objects.get(id=1).
  473. >>> Poll.objects.get(pk=1)
  474. <Poll: What's up?>
  475. # Make sure our custom method worked.
  476. >>> p = Poll.objects.get(pk=1)
  477. >>> p.was_published_today()
  478. False
  479. # Give the Poll a couple of Choices. The create call constructs a new
  480. # choice object, does the INSERT statement, adds the choice to the set
  481. # of available choices and returns the new Choice object. Django creates
  482. # a set to hold the "other side" of a ForeignKey relation
  483. # (e.g. a poll's choices) which can be accessed via the API.
  484. >>> p = Poll.objects.get(pk=1)
  485. # Display any choices from the related object set -- none so far.
  486. >>> p.choice_set.all()
  487. []
  488. # Create three choices.
  489. >>> p.choice_set.create(choice='Not much', votes=0)
  490. <Choice: Not much>
  491. >>> p.choice_set.create(choice='The sky', votes=0)
  492. <Choice: The sky>
  493. >>> c = p.choice_set.create(choice='Just hacking again', votes=0)
  494. # Choice objects have API access to their related Poll objects.
  495. >>> c.poll
  496. <Poll: What's up?>
  497. # And vice versa: Poll objects get access to Choice objects.
  498. >>> p.choice_set.all()
  499. [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]
  500. >>> p.choice_set.count()
  501. 3
  502. # The API automatically follows relationships as far as you need.
  503. # Use double underscores to separate relationships.
  504. # This works as many levels deep as you want; there's no limit.
  505. # Find all Choices for any poll whose pub_date is in 2007.
  506. >>> Choice.objects.filter(poll__pub_date__year=2007)
  507. [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]
  508. # Let's delete one of the choices. Use delete() for that.
  509. >>> c = p.choice_set.filter(choice__startswith='Just hacking')
  510. >>> c.delete()
  511. For more information on model relations, see :doc:`Accessing related objects
  512. </ref/models/relations>`. For full details on the database API, see our
  513. :doc:`Database API reference </topics/db/queries>`.
  514. When you're comfortable with the API, read :doc:`part 2 of this tutorial
  515. </intro/tutorial02>` to get Django's automatic admin working.