-
Notifications
You must be signed in to change notification settings - Fork 30
5.0 step7 correction
Add the following method in library.book
:
@fields.depends('description', 'summary')
def on_change_with_description(self):
if self.description:
return self.description
if not self.summary:
return ''
return self.summary.split('.')[0]
The point here is to set the description
field only if it is not yet set
(hence the first if
statement), and to extract some value from the
summary
field if it is set.
This pattern is useful to initialize fields from other fields, while still
maintaining the possibility to completely change its value. The first if
makes sure that a written down value will be kept even if the on_change
is
later triggered a second time.
Here we want to modify the value of the genre
field depending on that of
the editor
field. This could be done by using a on_change_with
on
genre
, or a on_change
on editor. We are going to use the latter,
because the editor
field may later trigger other modifications (though
there is no real "best" choice with the current elements):
@fields.depends('editor', 'genre')
def on_change_editor(self):
if not self.editor:
return
if self.genre and self.genre not in self.editor.genres:
self.genre = None
if not self.genre and len(self.editor.genres) == 1:
self.genre = self.editor.genres[0]
See how we can use the genres
field of self.editor
? This is because
the editor
record exists "outside" the library.book
model. If the user
modifies it, the modification is saved as soon as the user validates, whereas
the author
field (if the book is created from the One2Many
field on
library.author
) may be "currently being created", so there is the risk of
accessing a "not yet set" field.
This is a default
method in library.book
:
@classmethod
def default_exemplaries(cls):
return [{}]
We explained that the expected return values for One2Many
field is a list
of dictionaries. So here we create an empty dictionary (there aren't any value
that we can set, empty will be enough).
Remember what we said about consistency? How about making sure the
number_of_exemplaries
field is up to date?
@fields.depends('exemplaries')
def on_change_with_number_of_exemplaries(self):
return len(self.exemplaries or [])
You could say "Hey, that could be used as a getter", and you would be right.
However, we wrote an optimized classmethod as getter, so it would be
counter-productive to replace it with an instance method. Remember that you do
not have to use a on_change_with
as a getter if it does not suit your
needs, it is just a nice possibility that may make your code simpler.