Background Image
Table of Contents Table of Contents
Previous Page  378 / 478 Next Page
Information
Show Menu
Previous Page 378 / 478 Next Page
Page Background

def

get_absolute_url

(

self

):

return

reverse

(

'view_list'

,

args

=

[

self

.

id

])

def

create_new

():

pass

And after a few steps, we should end up with a form save method like this:

lists/forms.py (ch19l025).

class

NewListForm

(

ItemForm

):

def

save

(

self

,

owner

):

if

owner

.

is_authenticated

():

List

.

create_new

(

first_item_text

=

self

.

cleaned_data

[

'text'

],

owner

=

owner

)

else

:

List

.

create_new

(

first_item_text

=

self

.

cleaned_data

[

'text'

])

And passing tests:

$

python3 manage.py test lists

Ran 44 tests in 0.192s

OK

Hiding ORM Code Behind Helper Methods

One of the techniques that emerged from our use of isolated tests was the “ORM helper

method”.

Django’s ORM lets you get things done quickly with a reasonably readable syntax (it’s

certainly much nicer than raw SQL!). But some people like to try and minimise the

amount of ORM code in the application—particularly removing it from the views and

forms layers.

One reason is that it makes it much easier to test those layers. But another is that it forces

us to build helper functions that express our domain logic more clearly. Compare:

list_

=

List

()

list_

.

save

()

item

=

Item

()

item

.

list

=

list_

item

.

text

=

self

.

cleaned_data

[

'text'

]

item

.

save

()

With:

List

.

create_new

(

first_item_text

=

self

.

cleaned_data

[

'text'

])

This also applies to read queries as well as write. Imagine something like this:

Book

.

objects

.

filter

(

in_print

=

True

,

pub_date__lte

=

datetime

.

today

())

Versus a helper method, like:

Book

.

all_available_books

()

350

|

Chapter 19: Test Isolation, and “Listening to Your Tests”