[Fixed]-Getting data from multiple databases with same tablenames in django

6👍

Assuming that you have set up your multiple databases correctly:

  1. Have you tried to add a Custom Router?
    If not follow the example given on the documentation link.

  2. Have you tried to use a Custom Manager for your models?

    Create a manager for each model, like this:

    class YourModelManagerX(models.Manager):
        def get_queryset(self, *args, **kwargs):
            return super().get_queryset(*args, **kwargs).using('your_db_X')
    

    And then add it to your appropriate model as the objects field:

    class YourModel(models.Model):
        ...
        fields
        ...
        objects = YourManagerX()
    
        class Meta:
            managed = False
    

You may need to try both at once.

1👍

If db1.Members and db3.Members have the same definition, you do not have to redeclare the Members class separately for each database.

Models.py

...
class Members(models.Model): # Only declared once ever!
    ....

then,

from Models import Members

context['db1_data'] = Members.objects.using('db1').filter...
context['db3_data'] = Members.objects.using('db3').filter...

... # continue processing

Shouldn’t from ..models.db1 and from ..models.db2 be clear enough for django to spot the difference between the two models?

Django Models are not database-specific, more like schema-specific, so if you have the same table in two different databases, one class extending model.Models suffices. Then, when you attempt to retrieve the objects, either specify the database with using(), or using routers, which you can read about in the Django docs https://docs.djangoproject.com/en/2.0/topics/db/multi-db/#an-example

Leave a comment