PageRenderTime 174ms CodeModel.GetById 12ms RepoModel.GetById 2ms app.codeStats 1ms

/docs/intro/tutorial01.txt

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