Service-Repository Pattern Implementation In Django For Your APIs
Imagine that you have a Django app with a views.py file, And you put all the logics of your APIs from database stuff to email sending and …
The problem with such a code is that at some point of time this file gets too large and there are a lot of unrelated logics in it.
The problems with this type of code includes:
To address these problems there is a design pattern that separates the logic and it's called "Service Repository Pattern".
Let's see an example of it in an API in Django.
Step 1: Create a services directory in your Django app with __init__.py file.
Step 2: Create a file named "user_service.py":
Step 3: Create a directory called "repositories" in your Django app and then create two files with the names "__init__.py" and "user_repository.py" in it.
Step 4: Create your Data Access login in your repository file.
You can see that we put database logic to get a user from database or creating a user in this file. This is a simple example, Imagine when you have a longer database logic.
Step 5: Create your service layer in "user_service.py" file.
Step 6: Create you views logic:
And that's it, You can use this pattern to have a more readable and testable code.
Hope you've enjoyed it.
Thanks for reading.
Updated : 12-12-2023
Note: This is a simple implementation of the pattern, and it does not have a robust dependency injection as I didn't completely implemented the constructor injection but wanted to show you a grasp of it.
Backend Developer at Intelligenia
1 个月Why not use managers?
Software Engineer | AI & ML enthusiast
10 个月Why did you not build UserRepository as an abstract class using the ABC class?
Student at Ho Chi Minh City University of Technology
11 个月How can you test it if you can't mock the dependency, like repository and service??
Senior Backend Developer @ RIGT OFFICIAL
1 年What about dependency injection and DI Container?
Software Engineer
1 年Very useful ????