首页 > 解决方案 > Wagtail - 设置多个数据库

问题描述

我需要在 Wagtail 中设置多个数据库,但很难在我的辅助数据库中显示该表。

我已经完成了以下步骤(代码如下): 1. 创建了一个 models.py 文件 2. 创建了一个 wagtail_hooks.py 3. 在 base.py 中创建了一个额外的数据库引用

我期待我的 mysql 表(品牌)出现在 Wagtail CMS 中,但使用的是默认数据库(sqllite)。(没有返回错误信息)

参考代码:

模型.py

from django.db import models
from wagtail.core.models import Page
from wagtail.core.fields import RichTextField
from wagtail.admin.edit_handlers import FieldPanel

class Brand(models.Model):
    brandsid = models.AutoField(primary_key=True)
    brand = models.CharField(max_length=50, blank=False, null=False)
    class Meta:
        managed = True
        db_table = 'brands'
    panels = [
        FieldPanel('brand'),
    ]

wagtail_hooks.py

from wagtail.contrib.modeladmin.options import (
    ModelAdmin, modeladmin_register)
from .models import Brand


class BrandAdmin(ModelAdmin):
    model = Brand
    menu_label = 'Brands'  # ditch this to use verbose_name_plural from model
    menu_icon = 'pilcrow'  # change as required
    menu_order = 200  # will put in 3rd place (000 being 1st, 100 2nd)
    add_to_settings_menu = False  # or True to add your model to the Settings sub-menu
    exclude_from_explorer = False # or True to exclude pages of this type from Wagtail's explorer view
    list_display = ('brand', 'brandurl',)
    list_filter = ('brand',)
    search_fields = ('brand', 'brandurl',)

# Now you just need to register your customised ModelAdmin class with Wagtail
modeladmin_register(BrandAdmin)

base.py(摘录)

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

标签: wagtail

解决方案


这里的解决方案是我需要在这里使用 django 文档中的说明: https ://docs.djangoproject.com/en/3.0/topics/db/multi-db/

除了我上面的设置:

我将此添加到 base.py:

DATABASE_ROUTERS = ['routers.DbRouter']

然后在我的项目根目录中创建了一个 routers.py 文件:

class DbRouter:
    def db_for_read(self, model, **hints):
        # print(model._meta.app_label)
        if model._meta.app_label == 'brands':
            return 'mysql'
        return None

    def db_for_write(self, model, **hints):
        if model._meta.app_label == 'brands':
            return 'mysql'
        return None

    def allow_relation(self, obj1, obj2, **hints):
        if obj1._meta.app_label == 'brands' or \
           obj2._meta.app_label == 'brands':
           return True
        return None

    def allow_migrate(self, db, app_label, model_name=None, **hints):
        if app_label == 'brands':
            return db == 'mysql'
        return None

我还可以通过在函数中发出 print(model._meta.app_label) 命令并检查 runserver 的控制台输出来测试它是否命中了 routers.py 文件,这有助于获得正确的设置。


推荐阅读