diff options
Diffstat (limited to 'docs/intro/tutorial01.txt')
| -rw-r--r-- | docs/intro/tutorial01.txt | 136 |
1 files changed, 69 insertions, 67 deletions
diff --git a/docs/intro/tutorial01.txt b/docs/intro/tutorial01.txt index b99d3be3e2..19ecc5ebee 100644 --- a/docs/intro/tutorial01.txt +++ b/docs/intro/tutorial01.txt @@ -331,22 +331,24 @@ The first step in writing a database Web app in Django is to define your models the :ref:`DRY Principle <dry>`. The goal is to define your data model in one place and automatically derive things from it. -In our simple poll app, we'll create two models: ``Poll`` and ``Choice``. -A ``Poll`` has a question and a publication date. A ``Choice`` has two fields: +In our simple poll app, we'll create two models: ``Question`` and ``Choice``. +A ``Question`` has a question and a publication date. A ``Choice`` has two fields: the text of the choice and a vote tally. Each ``Choice`` is associated with a -``Poll``. +``Question``. These concepts are represented by simple Python classes. Edit the :file:`polls/models.py` file so it looks like this:: from django.db import models - class Poll(models.Model): - question = models.CharField(max_length=200) + + class Question(models.Model): + question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') + class Choice(models.Model): - poll = models.ForeignKey(Poll) + question = models.ForeignKey(Question) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) @@ -359,7 +361,7 @@ class -- e.g., :class:`~django.db.models.CharField` for character fields and :class:`~django.db.models.DateTimeField` for datetimes. This tells Django what type of data each field holds. -The name of each :class:`~django.db.models.Field` instance (e.g. ``question`` or +The name of each :class:`~django.db.models.Field` instance (e.g. ``question_text`` or ``pub_date``) is the field's name, in machine-friendly format. You'll use this value in your Python code, and your database will use it as the column name. @@ -367,7 +369,7 @@ You can use an optional first positional argument to a :class:`~django.db.models.Field` to designate a human-readable name. That's used in a couple of introspective parts of Django, and it doubles as documentation. If this field isn't provided, Django will use the machine-readable name. In this -example, we've only defined a human-readable name for ``Poll.pub_date``. For all +example, we've only defined a human-readable name for ``Question.pub_date``. For all other fields in this model, the field's machine-readable name will suffice as its human-readable name. @@ -382,7 +384,7 @@ this case, we've set the :attr:`~django.db.models.Field.default` value of Finally, note a relationship is defined, using :class:`~django.db.models.ForeignKey`. That tells Django each ``Choice`` is related -to a single ``Poll``. Django supports all the common database relationships: +to a single ``Question``. Django supports all the common database relationships: many-to-ones, many-to-manys and one-to-ones. .. _`Python path`: http://docs.python.org/tutorial/modules.html#the-module-search-path @@ -394,7 +396,7 @@ That small bit of model code gives Django a lot of information. With it, Django is able to: * Create a database schema (``CREATE TABLE`` statements) for this app. -* Create a Python database-access API for accessing ``Poll`` and ``Choice`` objects. +* Create a Python database-access API for accessing ``Question`` and ``Choice`` objects. But first we need to tell our project that the ``polls`` app is installed. @@ -430,14 +432,14 @@ statements for the polls app): .. code-block:: sql BEGIN; - CREATE TABLE "polls_poll" ( + CREATE TABLE "polls_question" ( "id" integer NOT NULL PRIMARY KEY, - "question" varchar(200) NOT NULL, + "question_text" varchar(200) NOT NULL, "pub_date" datetime NOT NULL ); CREATE TABLE "polls_choice" ( "id" integer NOT NULL PRIMARY KEY, - "poll_id" integer NOT NULL REFERENCES "polls_poll" ("id"), + "question_id" integer NOT NULL REFERENCES "polls_poll" ("id"), "choice_text" varchar(200) NOT NULL, "votes" integer NOT NULL ); @@ -449,7 +451,7 @@ Note the following: example above is generated for SQLite. * Table names are automatically generated by combining the name of the app - (``polls``) and the lowercase name of the model -- ``poll`` and + (``polls``) and the lowercase name of the model -- ``question`` and ``choice``. (You can override this behavior.) * Primary keys (IDs) are added automatically. (You can override this, too.) @@ -537,57 +539,57 @@ the Python import path to your :file:`mysite/settings.py` file. Once you're in the shell, explore the :doc:`database API </topics/db/queries>`:: - >>> from polls.models import Poll, Choice # Import the model classes we just wrote. + >>> from polls.models import Question, Choice # Import the model classes we just wrote. - # No polls are in the system yet. - >>> Poll.objects.all() + # No questions are in the system yet. + >>> Question.objects.all() [] - # Create a new Poll. + # Create a new Question. # Support for time zones is enabled in the default settings file, so # Django expects a datetime with tzinfo for pub_date. Use timezone.now() # instead of datetime.datetime.now() and it will do the right thing. >>> from django.utils import timezone - >>> p = Poll(question="What's new?", pub_date=timezone.now()) + >>> q = Question(question_text="What's new?", pub_date=timezone.now()) # Save the object into the database. You have to call save() explicitly. - >>> p.save() + >>> q.save() # Now it has an ID. Note that this might say "1L" instead of "1", depending # on which database you're using. That's no biggie; it just means your # database backend prefers to return integers as Python long integer # objects. - >>> p.id + >>> q.id 1 # Access database columns via Python attributes. - >>> p.question + >>> q.question_text "What's new?" - >>> p.pub_date + >>> q.pub_date datetime.datetime(2012, 2, 26, 13, 0, 0, 775217, tzinfo=<UTC>) # Change values by changing the attributes, then calling save(). - >>> p.question = "What's up?" - >>> p.save() + >>> q.question_text = "What's up?" + >>> q.save() - # objects.all() displays all the polls in the database. - >>> Poll.objects.all() - [<Poll: Poll object>] + # objects.all() displays all the questions in the database. + >>> Question.objects.all() + [<Question: Question object>] -Wait a minute. ``<Poll: Poll object>`` is, utterly, an unhelpful representation -of this object. Let's fix that by editing the polls model (in the +Wait a minute. ``<Question: Question object>`` is, utterly, an unhelpful representation +of this object. Let's fix that by editing the ``Question`` model (in the ``polls/models.py`` file) and adding a -:meth:`~django.db.models.Model.__unicode__` method to both ``Poll`` and +:meth:`~django.db.models.Model.__unicode__` method to both ``Question`` and ``Choice``. On Python 3, simply replace ``__unicode__`` by ``__str__`` in the following example:: from django.db import models - class Poll(models.Model): + class Question(models.Model): # ... def __unicode__(self): # Python 3: def __str__(self): - return self.question + return self.question_text class Choice(models.Model): # ... @@ -629,7 +631,7 @@ demonstration:: import datetime from django.utils import timezone # ... - class Poll(models.Model): + class Question(models.Model): # ... def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) @@ -643,80 +645,80 @@ the :doc:`time zone support docs </topics/i18n/timezones>`. Save these changes and start a new Python interactive shell by running ``python manage.py shell`` again:: - >>> from polls.models import Poll, Choice + >>> from polls.models import Question, Choice # Make sure our __unicode__() addition worked. - >>> Poll.objects.all() - [<Poll: What's up?>] + >>> Question.objects.all() + [<Question: What's up?>] # Django provides a rich database lookup API that's entirely driven by # keyword arguments. - >>> Poll.objects.filter(id=1) - [<Poll: What's up?>] - >>> Poll.objects.filter(question__startswith='What') - [<Poll: What's up?>] + >>> Question.objects.filter(id=1) + [<Question: What's up?>] + >>> Question.objects.filter(question_text__startswith='What') + [<Question: What's up?>] - # Get the poll that was published this year. + # Get the question that was published this year. >>> from django.utils import timezone >>> current_year = timezone.now().year - >>> Poll.objects.get(pub_date__year=current_year) - <Poll: What's up?> + >>> Question.objects.get(pub_date__year=current_year) + <Question: What's up?> # Request an ID that doesn't exist, this will raise an exception. - >>> Poll.objects.get(id=2) + >>> Question.objects.get(id=2) Traceback (most recent call last): ... - DoesNotExist: Poll matching query does not exist. Lookup parameters were {'id': 2} + DoesNotExist: Question matching query does not exist. Lookup parameters were {'id': 2} # Lookup by a primary key is the most common case, so Django provides a # shortcut for primary-key exact lookups. - # The following is identical to Poll.objects.get(id=1). - >>> Poll.objects.get(pk=1) - <Poll: What's up?> + # The following is identical to Question.objects.get(id=1). + >>> Question.objects.get(pk=1) + <Question: What's up?> # Make sure our custom method worked. - >>> p = Poll.objects.get(pk=1) - >>> p.was_published_recently() + >>> q = Question.objects.get(pk=1) + >>> q.was_published_recently() True - # Give the Poll a couple of Choices. The create call constructs a new + # Give the Question a couple of Choices. The create call constructs a new # Choice object, does the INSERT statement, adds the choice to the set # of available choices and returns the new Choice object. Django creates # a set to hold the "other side" of a ForeignKey relation - # (e.g. a poll's choices) which can be accessed via the API. - >>> p = Poll.objects.get(pk=1) + # (e.g. a question's choice) which can be accessed via the API. + >>> q = Question.objects.get(pk=1) # Display any choices from the related object set -- none so far. - >>> p.choice_set.all() + >>> q.choice_set.all() [] # Create three choices. - >>> p.choice_set.create(choice_text='Not much', votes=0) + >>> q.choice_set.create(choice_text='Not much', votes=0) <Choice: Not much> - >>> p.choice_set.create(choice_text='The sky', votes=0) + >>> q.choice_set.create(choice_text='The sky', votes=0) <Choice: The sky> - >>> c = p.choice_set.create(choice_text='Just hacking again', votes=0) + >>> c = q.choice_set.create(choice_text='Just hacking again', votes=0) - # Choice objects have API access to their related Poll objects. - >>> c.poll - <Poll: What's up?> + # Choice objects have API access to their related Question objects. + >>> c.question + <Question: What's up?> - # And vice versa: Poll objects get access to Choice objects. - >>> p.choice_set.all() + # And vice versa: Question objects get access to Choice objects. + >>> q.choice_set.all() [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>] - >>> p.choice_set.count() + >>> q.choice_set.count() 3 # The API automatically follows relationships as far as you need. # Use double underscores to separate relationships. # This works as many levels deep as you want; there's no limit. - # Find all Choices for any poll whose pub_date is in this year + # Find all Choices for any question whose pub_date is in this year # (reusing the 'current_year' variable we created above). - >>> Choice.objects.filter(poll__pub_date__year=current_year) + >>> Choice.objects.filter(question__pub_date__year=current_year) [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>] # Let's delete one of the choices. Use delete() for that. - >>> c = p.choice_set.filter(choice_text__startswith='Just hacking') + >>> c = q.choice_set.filter(choice_text__startswith='Just hacking') >>> c.delete() For more information on model relations, see :doc:`Accessing related objects |
