tutorial01.txt 27 KB

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