在django admin中公开多个数据库

时间:2016-09-19 08:31:49

标签: python django django-admin

我的用例要求我在我的django项目的管理站点中公开多个数据库。这是否在此链接之后:https://docs.djangoproject.com/en/dev/topics/db/multi-db/#exposing-multiple-databases-in-django-s-admin-interface

以下是使用的代码:

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(MultiDBModelAdmin, self).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(MultiDBModelAdmin, self).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(MultiDBModelAdmin, self).formfield_for_manytomany(db_field, request, using=self.using, **kwargs)

然后:

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

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

示例的文档说明:此示例设置了两个管理站点。在第一个站点上,公开了Author和Publisher对象;发布者对象具有表格内联,显示该发布者发布的书籍。第二个网站只公开发布商,没有内联。

我似乎没有发现任何地方:我如何访问其他“网站”?必须使用哪个URL来查看在另一个“网站”中公开的表格?应该是直截了当的,但我似乎无法在任何地方找到它。

1 个答案:

答案 0 :(得分:1)

您需要为管理网站添加网址格式,类似于启用常规网站的方式:

# urls.py
from django.conf.urls import url
from django.contrib import admin
from myapp.admin import othersite

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^otheradmin/', othersite.urls),
]

然后,您可以使用您使用的任何网址访问其他管理员。在这种情况下,/otheradmin/

此语法适用于Django 1.10+。在早期版本的Django上,您使用include(othersite.urls)而不是othersite.urls