I need to manage multiple databases within Django Admin. My two databases named 'local' and 'server' are defined in the settings file. Since Django doesn't allow to add several times the same model with different ModelAdmin
, I am creating two instances of admin.AdminSite
.
Here is the code of the admin.py
file:
from core.models import MyModel
from django.contrib import admin
server_site = admin.AdminSite('server')
local_site = admin.AdminSite('local')
class MultiDBModelAdmin(admin.ModelAdmin):
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(MultiDBModelAdmin1, self).get_queryset(request).using(self.using)
def formfield_for_foreignkey(self, db_field, request=None, **kwargs):
# Tell Django to populate ForeignKey widgets using a query
# on the 'other' database.
return super(MultiDBModelAdmin1, self).formfield_for_foreignkey(db_field, request=request, using=self.using, **kwargs)
def formfield_for_manytomany(self, db_field, request=None, **kwargs):
# Tell Django to populate ManyToMany widgets using a query
# on the 'other' database.
return super(MultiDBModelAdmin1, self).formfield_for_manytomany(db_field, request=request, using=self.using, **kwargs)
class MultiDBModelAdmin1(MultiDBModelAdmin):
# A handy constant for the name of the alternate database.
using = 'server'
class MultiDBModelAdmin2(MultiDBModelAdmin):
# A handy constant for the name of the alternate database.
using = 'local'
local_site.register(MyModel, MultiDBModelAdmin1)
server_site.register(MyModel, MultiDBModelAdmin2)
and here is the urls.py
file:
from django.conf.urls import patterns, include, url
from core.admin import local_site, server_site
urlpatterns = patterns('',
url(r'^admin/', include(local_site.urls)),
url(r'^serveradmin/', include(server_site.urls)),
[...]
)
I can access the admin panel using both the admin/
and serveradmin/
URLs, however the content is the very same: the administration panel is using the 'local' database, regardless of the admin panel I access. How come Django doesn't discriminate the two?