2014-01-09 52 views
0

我使用Django管理,以方便編輯數據庫。最近,我們添加了另一個數據庫,因此使用設置文件中的DATABASES中的默認值將不再有意義。Django管理指定的數據庫(不是默認的)

我現在有這在我的settings.py文件:

DATABASES = { 
    'default': {}, 
    'animal_tracking': { 
     'ENGINE':'django.db.backends.mysql', 
     'NAME': 'AnimalTracking', 
     'USER': 'foo', 
     'PASSWORD': 'bar', 
     'HOST': '127.0.0.1', 
     'PORT': '3306', 
    }, 
    'animal_information': { 
     'ENGINE':'django.db.backends.mysql', 
     'NAME': 'AnimalInformation', 
     'USER': 'foo', 
     'PASSWORD': 'bar', 
     'HOST': '127.0.0.1', 
     'PORT': '3306', 
    }, 
} 

我的admin.py文件包含:

from django.contrib import admin 
from animal_tracking.models import at_animal_types, at_animals 
# Register your models here. 

class AnimalTypesAdmin(admin.ModelAdmin): 
    # Sets how the fields are displayed in the add/change section. 
    fieldsets = [ 
     (None,    {'fields': ['type', ]}), 
    ] 
    # Sets what fields to be displayed in the change (view) section. 
    list_display = ('type',) 
# Registers the current model administration to the admin page. 
admin.site.register(at_animal_types, AnimalTypesAdmin) 

class AnimalsAdmin(admin.ModelAdmin): 
    # Sets how the fields are displayed in the add/change section. 
    fieldsets = [ 
     (None,    {'fields': ['tracker_id', 'type', ]}), 
     ('Log information (should not change)', {'fields': ['last_log', 'last_bat', 'last_lat', 'last_lon', ], 'classes': ['collapse']}), 
    ] 
    # Sets what fields to be displayed in the change (view) section. 
    list_display = ('tracker_id', 'type', 'last_log', 'last_bat', 'last_lat', 'last_lon',) 
    # Sets what fields to allow filtering by. 
    list_filter = ['type', ] 
    # Sets what fields to allow searching by. Use table__field if foreign key. 
    search_fields = ['tracker_id', 'type__type', ] 
# Registers the current model administration to the admin page. 
admin.site.register(at_animals, AnimalsAdmin) 

最初,管理部分將使用默認的數據庫連接。但現在,我刪除了默認,並添加了其他2個數據庫,我收到以下錯誤:

Django error.

如果我複製animal_tracking默認的設置,它的工作原理。因此我的問題是:

如何指定django admin應使用哪個數據庫?

謝謝!

回答

1

你會更好地指定默認數據庫,如果你保留默認空白,你應該寫db db routers

在您的管理員

,你可以使用任何你喜歡的分貝:

class AnimalTypesAdmin(admin.ModelAdmin): 
    using = 'animal_tracking' 
    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) 

save_modeldelete_modelformfield_for_foreignkeyformfield_for_manytomany也應該重寫比如上例中this