Search code examples
djangodjango-modelsdjango-ormdjango-databasemulti-database

How to always use a specific DB connection for certain django model?


I will add a procedure to a django app where I need to store data but only for a few hours, also I don't wat to add another table to my db schema (which is kind of big), I'm thinking to use redis for the task, in the end what I want to achieve is to have a Transfer model, and I want this model always be using another database for its CRUD operations.

Example:

Transfer.objects.all()  # Always be the same as Transfer.objects.using('redis').all()
OtherModel.objects.all()  # Always use default DB

# Same for save
transfer_instance.save()  # Always translate to transfer_instance.save(using='redis')
other_instance.save()  # Work as usuall using default DB

How can I achieve this? I don't mind using obscure trickery as long as it works.

Thanks!


Solution

  • You will need to use a Database Router to achieve what you need.

    Here is the official documentation for Using Database Routers