• 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

  • 相关阅读:
    MISC | ctfshow 31
    010editor 没有分块高亮显示了
    BUUCTF | [网鼎杯 2020 朱雀组]phpweb
    python2与python3共存后,如何使用
    kali2020 装不上docker
    php代码审计整理
    [MRCTF2020]Ezpop
    kali没有tcptraceroute如何安装
    [BUUCTF] 真的很杂
    【弱网测试】备份弱网测试相关数据
  • 原文地址:https://www.cnblogs.com/wumingxiaoyao/p/6952117.html
Copyright © 2020-2023  润新知