Fixed #21951 -- Updated docs to use __str__ for Python 3

Thanks Tim Graham for the report and recommendations
This commit is contained in:
Alasdair Nicol 2014-02-09 11:38:13 +00:00 committed by Tim Graham
parent c3434fed5b
commit 8aa1efff6d
20 changed files with 71 additions and 72 deletions

View file

@ -463,9 +463,29 @@ the conversion to string objects when required.
.. method:: Model.__str__()
The ``__str__()`` method is called whenever you call ``str()`` on an object. The main use for this method directly inside Django is when the ``repr()`` output of a model is displayed anywhere (for example, in debugging output).
Thus, you should return a nice, human-readable string for the object's
``__str__()``. It isn't required to put ``__str__()`` methods everywhere if you have sensible :meth:`~Model.__unicode__()` methods.
The ``__str__()`` method is called whenever you call ``str()`` on an
object. In Python 3, Django uses ``str(obj)`` in a number of
places. Most notably, to display an object in the Django admin site
and as the value inserted into a template when it displays an
object. Thus, you should always return a nice, human-readable
representation of the model from the ``__str__()`` method.
For example::
from django.db import models
class Person(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
def __str__(self):
return '%s %s' % (self.first_name, self.last_name)
In Python 2, the main use of ``__str__`` directly inside Django is
when the ``repr()`` output of a model is displayed anywhere (for
example, in debugging output). It isn't required to put ``__str__()``
methods everywhere if you have sensible :meth:`~Model.__unicode__()`
methods.
The previous :meth:`~Model.__unicode__()` example could be similarly written
using ``__str__()`` like this::

View file

@ -812,17 +812,16 @@ For example, suppose you have these models::
name = models.CharField(max_length=50)
toppings = models.ManyToManyField(Topping)
# On Python 3: def __str__(self):
def __unicode__(self):
return u"%s (%s)" % (self.name, u", ".join([topping.name
for topping in self.toppings.all()]))
def __str__(self): # __unicode__ on Python 2
return "%s (%s)" % (self.name, ", ".join([topping.name
for topping in self.toppings.all()]))
and run::
>>> Pizza.objects.all()
[u"Hawaiian (ham, pineapple)", u"Seafood (prawns, smoked salmon)"...
["Hawaiian (ham, pineapple)", "Seafood (prawns, smoked salmon)"...
The problem with this is that every time ``Pizza.__unicode__()`` asks for
The problem with this is that every time ``Pizza.__str__()`` asks for
``self.toppings.all()`` it has to query the database, so
``Pizza.objects.all()`` will run a query on the Toppings table for **every**
item in the Pizza ``QuerySet``.