我们可以在Django的models.py中定义数据库名称吗?

时间:2018-12-26 09:51:27

标签: django django-models django-forms django-views

我在settings.py中定义了多个数据库。在models.py中,我必须使用已定义的datbase而不是默认数据库中的auth_user表,我们如何在models.py中进行定义? 我在settings.py中定义了如下数据库:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'sources',
        'USER': 'root',
        'PASSWORD': 'cdffd@123',
        'HOST': 'xx.xx.xx.xxx',
        'PORT': '3306',
    },
    'abc': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'customers',
        'USER': 'root',
        'PASSWORD': 'dsgfsd@123',
        'HOST': 'xx.xx.xx.xxx',
        'PORT': '3306',
    },
    'xyz': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'users',
        'USER': 'root',
        'PASSWORD': 'ewet@123',
        'HOST': 'xx.xx.xx.xxx',
        'PORT': '3306',
    },
}

在我的models.py中,我定义了以下用户模型:

class User(AbstractBaseUser, PermissionsMixin, BaseUserManager):
    name_regex                  = RegexValidator(regex="^[a-zA-Z]+$",message="Enter only Alphabets")#regular expression for name
    email_regex                 = RegexValidator(regex="^\w.+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$",message="Enter valid Email Id")#regular expression for email
    password                    = models.CharField(_("Password"),max_length=128,default='')  
    last_login                  = models.DateTimeField(_('date Last Login'), null=True, blank=True)
    is_superuser                = models.BooleanField(_("Super User"),default=0)
    username                    = models.CharField(_('Username'), max_length=75,blank=True,null=True)
    first_name                  = models.CharField(_('First name'),default='',blank=True,null=True, max_length=20)
    last_name                   = models.CharField(_('Last name'),default='',blank=True,null=True,  max_length=20)
    email                       = models.EmailField(_('Enter your email address'),unique=True,max_length=254,error_messages={'unique':"Email ID already registered.",'invalid':'Enter valid Email ID'})
    is_staff                    = models.BooleanField(_('staff status'), default=False)
    is_active                   = models.BooleanField(_('active'), default=True)#A boolean attribute that indicates whether the user is considered “active”
    date_joined                 = models.DateTimeField(_('Date joined'))
    iRoleID                     = models.IntegerField(_("Role"),default=0) 
    iModifiedBy                 = models.IntegerField(_("Modified By"),blank=True,null=True)
    dtModifiedOn                = models.DateTimeField(_("Modified On"),blank=True,null=True)
    apitoken_validity           = models.IntegerField(default=0)
    authentication_type         = models.IntegerField(default=1)
    iMSISDN                     = models.IntegerField(_('Mobile Number'),default=0)
    objects = UserManager()
    USERNAME_FIELD = 'email'# unique identifier. The field must be unique
    REQUIRED_FIELDS = ['username']
    def __unicode__(self):
        return self.username    
    def __str__(self):
        return self.email
    class Meta:
        app_label = 'users'
        db_table = "auth_user"

默认情况下,它从定义为默认值的数据库中获取auth_user表。但是,我需要从xyz中定义的数据库中获取auth_user表。那可能吗?如果可能的话,我该怎么做?

1 个答案:

答案 0 :(得分:1)

您可以使用数据库路由器来做到这一点。

一个例子是:

class AuthRouter:
    """
    A router to control all database operations on models in the
    auth application.
    """
    def db_for_read(self, model, **hints):
        """
        Attempts to read auth models go to auth_db.
        """
        if model._meta.db_table == 'auth_users':
            return 'auth_db'
        return None

    def db_for_write(self, model, **hints):
        """
        Attempts to write auth models go to auth_db.
        """
        if model._meta.db_table == 'auth_users':
            return 'auth_db'
        return None

,然后使用

将其添加到settings.py
DATABASE_ROUTERS = ['path.to.AuthRouter']

ref:Django Documentation