使用数据库路由器时在Django中打印SQL查询

时间:2015-12-15 14:05:05

标签: django django-models django-queryset

我正在使用Django 1.8和Python 2.7。我想使用默认'以外的数据库。我们可以使用here描述的空白参数。我们称之为数据库' test'。为了使django工作,我需要做一些路由。现在,我只需将所有内容都安排到'测试' db喜欢这样:

class Router(object):
    def db_for_read(self, model, **hints):
        """
        Reads go to a randomly-chosen replica.
        """
        return 'test'

    def db_for_write(self, model, **hints):
        """
        Writes always go to primary.
        """
        return 'test'

    def allow_relation(self, obj1, obj2, **hints):
        """
        Relations between objects are allowed if both objects are
        in the primary/replica pool.
        """
        return True

    def allow_migrate(self, db, app_label, model=None, **hints):
        """
        All non-auth models end up in this pool.
        """
        return True


# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
DATABASE_ROUTERS = ['test123.settings.Router']
DATABASES = {
    'default': {},
    'test': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

我制作了一个简单的模型(取自Django教程):

from django.db import models

# Create your models here.
class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

我现在正在进行/运行适当的迁移。我可以在shell中进行Question.objects.all()等查询,返回[]。但是,现在当我拨打print Question.objects.all().query时,它会显示错误settings.DATABASES is improperly configured. Please supply the ENGINE value.我认为它正在使用'默认'数据库而不是'测试'数据库。有没有办法解决这个问题,所以我可以看到原始的SQL查询?

1 个答案:

答案 0 :(得分:1)

试试Model.objects.using('test').all().query

您可以使用using手动选择数据库。请参阅docs

<强>更新

仅提供ENGINE

DATABSES['default']

ImproperlyConfigured数据库default为空时,Django会在每个api函数上引发ENGINE异常。请参阅docstring here