Bläddra i källkod

Fixed #27953 -- Added instance's pk to Model.__str__().

Collin Anderson 8 år sedan
förälder
incheckning
1a49b89470
4 ändrade filer med 13 tillägg och 7 borttagningar
  1. 1 1
      django/db/models/base.py
  2. 4 4
      docs/intro/tutorial02.txt
  3. 3 0
      docs/releases/2.0.txt
  4. 5 2
      tests/str/tests.py

+ 1 - 1
django/db/models/base.py

@@ -505,7 +505,7 @@ class Model(metaclass=ModelBase):
         return '<%s: %s>' % (self.__class__.__name__, u)
 
     def __str__(self):
-        return '%s object' % self.__class__.__name__
+        return '%s object (%s)' % (self.__class__.__name__, self.pk)
 
     def __eq__(self, other):
         if not isinstance(other, Model):

+ 4 - 4
docs/intro/tutorial02.txt

@@ -437,11 +437,11 @@ Once you're in the shell, explore the :doc:`database API </topics/db/queries>`::
 
     # objects.all() displays all the questions in the database.
     >>> Question.objects.all()
-    <QuerySet [<Question: Question object>]>
+    <QuerySet [<Question: Question object (1)>]>
 
-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
+Wait a minute. ``<Question: Question object (1)>`` isn't a helpful
+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.__str__` method to both ``Question`` and
 ``Choice``:
 

+ 3 - 0
docs/releases/2.0.txt

@@ -441,6 +441,9 @@ Miscellaneous
   :class:`~django.views.i18n.JavaScriptCatalog` view now raises ``ValueError``
   instead of passing silently.
 
+* A model instance's primary key now appears in the default ``Model.__str__()``
+  method, e.g. ``Question object (1)``.
+
 .. _deprecated-features-2.0:
 
 Features deprecated in 2.0

+ 5 - 2
tests/str/tests.py

@@ -30,5 +30,8 @@ class SimpleTests(TestCase):
         # coerce the returned value.
         self.assertIsInstance(obj.__str__(), str)
         self.assertIsInstance(obj.__repr__(), str)
-        self.assertEqual(str(obj), 'Default object')
-        self.assertEqual(repr(obj), '<Default: Default object>')
+        self.assertEqual(str(obj), 'Default object (None)')
+        self.assertEqual(repr(obj), '<Default: Default object (None)>')
+        obj2 = Default(pk=100)
+        self.assertEqual(str(obj2), 'Default object (100)')
+        self.assertEqual(repr(obj2), '<Default: Default object (100)>')