breaking up fat models

August 26, 2017

We have a Django application at work that gets all its data from a REST API (from another Django app). We have a models layer that defines model classes and deserialises them using the marshmallow library, along with “services” that fetch the data from the API and return instances of the model classes.

The model classes have got fairly big, as they can lazily load other models via the service classes. This leads to circular imports as the models need to use the service, which needs to create an instance of the model. Currently that is solved by the models importing the services at run time. And it’s likely to get more complex soon as we use new features of the API to get the related models inlined so as to reduce the number of HTTP requests required behind the scene.

So I’m thinking we should add a manager layer. I’m also thinking we drop the lazy loading and always ask for the linked set of models we need. A usage might be one of the following:

TaskManager.get_task_with_builds(task_id)

TaskManager.get_task(task_id, with_builds=True)

(I think I prefer the second, but more thought is required.)

Then the manager can import both the service and the model and the model doesn’t need to know about the service.

comments powered by Disqus