Django refactoring — how to split admin.py and models.py in 3 steps

Maria Bshara
2 min readOct 7, 2022

--

Recently I wrote a post about how to refactor Django models in a “divide-and-conquer” way. Check it if you’re into more significant refactoring.

Let’s say you’re not into such global changes but still your models.py is more than a thousand lines and you would like to split it into separate files fast and without fear to break the project. It’s actually very easy to do. In this mini-tutorial, we will spit admin.py and models.py into smaller, easy-maintainable, and understandable instances

0. We start with the huge models.py or/and admin.py.

1. First, create a folder called admin instead of admin.py and models instead of models.py.

2. Split the code into logical files inside the new folders and create __init__.py which imports classes from the new files. Try to avoid circular imports if you work with ForeignKeys for example

Though if you split the admin file I would recommend keeping admin.site.register (if you use it) in __init__.py for easier maintenance since you’ll have access to all the models from one file.

3. Delete the initial models.py or/and admin.py and we’re done!

--

--

Maria Bshara
Maria Bshara

Written by Maria Bshara

Backend Tech lead, Python engineer. Interested in AI and related topics 👾 Mostly writing about refactoring and python best practices :)