Django admin 使用多個數據庫


admin是django自帶的一個app,那它涉及的是對Model的所有對象進行增刪改查,如果model來自多個數據庫如何處理呢?

 

重寫admin.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(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)

  MultiDBModelAdmin類繼承admin.ModelAdmin

然后需要使用這個數據庫連接的model直接繼承這個類就可以了。

class UserInfoAdmin(MultiDBModelAdmin):
    list_display = ('user_name', 'user_email', 'user_mobile')

  

參考:https://docs.djangoproject.com/en/1.10/topics/db/multi-db/#topics-db-multi-db-routing


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM