Wagtail-设置多个数据库

问题描述 投票:1回答:1

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

我已完成以下步骤(下面的代码):1.创建了一个models.py文件2.创建了一个wagtail_hooks.py3.在base.py

中创建了一个附加的数据库引用

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

参考代码:

models.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
1个回答
0
投票

这里的解决方案是,我需要在这里使用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文件,这有助于获得正确的设置。

© www.soinside.com 2019 - 2024. All rights reserved.