Django Model.objects.all()返回意外的空QuerySet

时间:2018-02-27 03:22:23

标签: python mysql django django-models

我在尝试使用Django的MySQL数据库时遇到了一些问题。该数据库包含一个名为items的表。该数据库从开发系统导入到生产系统。除了其他团队使用的现有SQLite数据库外,此数据库是第二个数据库。有关于no such table的错误消息,但我能够使用this question解决此问题。然后我假设没有迁移错误。

MySQL数据库在开发系统中运行良好(使用python manage.py shell测试),但它在生产系统中不起作用(以相同的方式测试。)

我测试了导入:

$ python manage.py shell    

>> from project.models import Item

>> Item.objects.all()
<QuerySet []>

我创建了models.py文件:

$ python manage.py inspectdb > models.py

我验证了数据库和表items实际上包含记录。 (尽管某些字段存储为unicode文本,但如果这对情况有任何影响。)

以下是project/settings.py文件的一部分:

...
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    },
    'new_project': {
        'NAME': 'new_project',
        'ENGINE': 'django.db.backends.mysql',
        'USER': 'xxxxxxxx',
        'PASSWORD': 'xxxxxxxx',
    }
}
...

以下是生成的app/models.py

的一部分
...
class Item(models.Model):
    itemid = models.AutoField(db_column='ItemID', primary_key=True)  # Field name made lowercase.
    name = models.TextField(blank=True, null=True)
    category = models.TextField(blank=True, null=True)
    kind = models.TextField(blank=True, null=True)

    class Meta:
        managed = True
        db_table = 'items'
...

我将Django 2.0.2Python 3.6.3一起使用。

2 个答案:

答案 0 :(得分:1)

Django尝试找到与其模型匹配的表<app_name>_<model_name>,但您可以将此Meta类添加到Item类以更改Django的工作方式(或更改您的表名称)到project_items):

class Item(models.Model):
    ...
    class Meta:
        db_table = 'items'

答案 1 :(得分:1)

Django支持与多个数据库进行交互。这就是你在这里做的事情。要建立连接,您必须为所有应用的模型设置DATABASE_ROUTERS 例如DBRouter

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.app_label == 'auth':
            return 'auth_db'
        return None

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

    def allow_relation(self, obj1, obj2, **hints):
        """
        Allow relations if a model in the auth app is involved.
        """
        if obj1._meta.app_label == 'auth' or \
           obj2._meta.app_label == 'auth':
           return True
        return None

    def allow_migrate(self, db, app_label, model_name=None, **hints):
        """
        Make sure the auth app only appears in the 'auth_db'
        database.
        """
        if app_label == 'auth':
            return db == 'auth_db'
        return None


settings.pyDATABASE_ROUTERS = ['path.to.AuthRouter']中 您可以从django's official doc找到更多详细信息和信息。