tutorial01.txt 28 KB

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