Django4.0 多数据库-在Django管理界面中使用多数据库

2022-03-16 17:38 更新

Django的管理后台对多数据库没有明显的支持。如果要为路由指定的数据库以外的数据库提供模型的管理界面,你需要编写自定义的 ​ModelAdmin ​类,这个类将指示管理后台使用指定数据库的内容。

ModelAdmin ​对象有五种需要为多数据库支持定制的方法:

class MultiDBModelAdmin(admin.ModelAdmin):
    # A handy constant for the name of the alternate database.
    using = 'other'

    def save_model(self, request, obj, form, change):
        # Tell Django to save objects to the 'other' database.
        obj.save(using=self.using)

    def delete_model(self, request, obj):
        # Tell Django to delete objects from the 'other' database
        obj.delete(using=self.using)

    def get_queryset(self, request):
        # Tell Django to look for objects on the 'other' database.
        return super().get_queryset(request).using(self.using)

    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        # Tell Django to populate ForeignKey widgets using a query
        # on the 'other' database.
        return super().formfield_for_foreignkey(db_field, request, using=self.using, **kwargs)

    def formfield_for_manytomany(self, db_field, request, **kwargs):
        # Tell Django to populate ManyToMany widgets using a query
        # on the 'other' database.
        return super().formfield_for_manytomany(db_field, request, using=self.using, **kwargs)

此处提供的实现方法实现了多数据库策略,其中给定类型的所有对象保存在指定数据库上(比如所有 ​User ​对象在 ​other ​数据库中)。如果对多数据的使用很复杂,那么​ModelAdmin​将需要映射策略。
InlineModelAdmin ​对象可以以类似的方式处理。它们需要三个自定义的方法:

class MultiDBTabularInline(admin.TabularInline):
    using = 'other'

    def get_queryset(self, request):
        # Tell Django to look for inline objects on the 'other' database.
        return super().get_queryset(request).using(self.using)

    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        # Tell Django to populate ForeignKey widgets using a query
        # on the 'other' database.
        return super().formfield_for_foreignkey(db_field, request, using=self.using, **kwargs)

    def formfield_for_manytomany(self, db_field, request, **kwargs):
        # Tell Django to populate ManyToMany widgets using a query
        # on the 'other' database.
        return super().formfield_for_manytomany(db_field, request, using=self.using, **kwargs)

一旦编写了模型管理定义,就可以在任何 ​Admin ​实例中注册:

from django.contrib import admin

# Specialize the multi-db admin objects for use with specific models.
class BookInline(MultiDBTabularInline):
    model = Book

class PublisherAdmin(MultiDBModelAdmin):
    inlines = [BookInline]

admin.site.register(Author, MultiDBModelAdmin)
admin.site.register(Publisher, PublisherAdmin)

othersite = admin.AdminSite('othersite')
othersite.register(Publisher, MultiDBModelAdmin)

这个例子设置了两个管理长点。在第一个站点上,​Author ​和 ​Publisher ​对象是显式的;​Publisher ​对象有一个表格行来显示出版者的书籍。第二个站点只显示出版者,不显示内嵌。


以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号