Custom manager in Django MultiDB

I'am using MySQL and PostgreSQL in my Django project. Below are the settings:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql', 
        'NAME': 'mysql_db',
        'USER': 'username',
        'PASSWORD': 'password',
        'HOST': 'hostname',
        'PORT': '3306',
},
    'postgres_db': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'pgsql_db',
        'USER': 'username',
        'PASSWORD': 'password',
        'HOST': 'hostname',
        'PORT': '5432',
    }

}

And this is the sample model

from postgres_copy import CopyManager
class Items(models.Model):
    class params:
        db = "postgres_db"
    sales_value             = models.CharField(max_length=255, null=True, blank=True)
    primary_email           = models.CharField(max_length=255, null=True, blank=True)
    
    objects = CopyManager()

I want to use Items.objects.all().to_csv('./path/to/csv) this ORM to export model data to CSV. I have used this before in exporting large dataset to csv. But in this configuration it gives below error

psycopg2.errors.SyntaxError: syntax error at or near "."
LINE 1: COPY (SELECT `sales_item`.`id`, `sales_item`.`sales_value`,...

This seems to be an issue with multiDB. If I run this ORM in single DB configuration, or even if I set default alias on PostgreSQL this works fine.

CopyManager seems to be getting default alias somehow which I have no idea about.

How can I run this ORM in current settings without any issues? Any help would be appreciated.

Thanks in advance.

We use postgres and MariaDB in the same time in one project. I can say - you dont need any additional data manager, in your case it can be:

from django.db.import models

class ItemsQuerySetManager(models.Manager):

    def get_queryset(self, *args, **kwargs):
        return super().get_queryset(*args, **kwargs).using("postgres_db")


class Items(models.Model):

    sales_value = models.CharField(max_length=255, null=True, blank=True)
    primary_email = models.CharField(max_length=255, null=True, blank=True)
    
    objects = ItemsQuerySetManager()

more info here: https://docs.djangoproject.com/en/4.1/topics/db/multi-db/

Back to Top