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 queries.

We will then add it to the Library Books model.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset