Using abstract models for reusable model features
Sometimes, there is a particular feature that we want to be able to add to several different models. Repeating the same code in different files is a bad programming practice; it would be better to implement it once and reuse it.
Abstract models allow us to create a generic model that implements some features that can then be inherited by regular models in order to make that feature available.
As an example, we will implement a simple archive feature. It adds the active
field to the model (if it doesn't exist already) and makes an archive method available to toggle the active
flag. This works because active
is a magic field. If present in a model by default, the records with active=False
will be filtered out from the queries.
We will then add it to the Library Books
model.
Getting ready
We will continue using the my_library
add-on module from the previous recipe.
How to do it...
The archive feature certainly...