wagtail - 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'
}
}
解决方案
这里的解决方案是我需要在这里使用 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 文件,这有助于获得正确的设置。
推荐阅读
- node.js - 为什么 get route 显示 TypeError: Cannot read property 'title' of null 并导致网站崩溃?
- python - 调用 API 时如何解决 AttributeError?
- android - 处理来自后端作业的 Oath 2.0 授权
- mongodb - TypeORM 查询 MongoDB 日期时返回空数组
- outlook - 使用 REST API 的 Outlook Web 加载项在 Outlook for Windows 中刷新缓慢
- mysql - 从mysql查询在hive中实现不等式连接
- ios - 我们是否需要为 CocoaPods 和 Carthage 创建 iOS 通用框架?
- sql - 在 BigQuery 中,确定 UNION ALL 上的列何时不匹配
- c++ - 在 C++ 中格式化字符串时从双精度数中删除所有尾随零
- javascript - 如何在 Vue 组件中使用 Bootstrap?