A Little Digression on Queryset Ordering and String Representations
When we run the tests they reveal an unexpected failure:
======================================================================
FAIL: test_saving_and_retrieving_items
(lists.tests.test_models.ListAndItemModelsTest)
---------------------------------------------------------------------
Traceback (most recent call last):
File "/workspace/superlists/lists/tests/test_models.py", line 31, in
test_saving_and_retrieving_items
self.assertEqual(first_saved_item.text, 'The first (ever) list item')
AssertionError: 'Item the second' != 'The first (ever) list item'
- Item the second
[...]
Depending on your platform and its SQLite installation, you may not
see this error. You can follow along anyway; the code and tests are
interesting in their own right.
That’s a bit of a puzzler. A bit of print-based debugging:
lists/tests/test_models.py.
first_saved_item
=
saved_items
[
0
]
(
first_saved_item
.
text
)
second_saved_item
=
saved_items
[
1
]
(
second_saved_item
.
text
)
self
.
assertEqual
(
first_saved_item
.
text
,
'The first (ever) list item'
)
Will show us…
.....Item the second
The first (ever) list item
F.....
It looks like our uniqueness constraint has messed with the default ordering of queries
like
Item.objects.all()
. Although we already have a failing test, it’s best to add a new
test that explicitly tests for ordering:
lists/tests/test_models.py (ch09l032).
def
test_list_ordering
(
self
):
list1
=
List
.
objects
.
create
()
item1
=
Item
.
objects
.
create
(
list
=
list1
,
text
=
'i1'
)
item2
=
Item
.
objects
.
create
(
list
=
list1
,
text
=
'item 2'
)
item3
=
Item
.
objects
.
create
(
list
=
list1
,
text
=
'3'
)
self
.
assertEqual
(
Item
.
objects
.
all
(),
[
item1
,
item2
,
item3
]
)
That gives us a new failure, but it’s not a very readable one:
214
|
Chapter 12: More Advanced Forms