How to show all fields of model in admin page?

后端 未结 11 517
無奈伤痛
無奈伤痛 2021-01-30 16:25

here is the models page

In this picture, only the title shows up on here, I used:

 def __unicode__(self):
        return self.title;  

11条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-30 16:49

    Here is my approach, will work with any model class:

    MySpecialAdmin = lambda model: type('SubClass'+model.__name__, (admin.ModelAdmin,), {
        'list_display': [x.name for x in model._meta.fields],
        'list_select_related': [x.name for x in model._meta.fields if isinstance(x, (ManyToOneRel, ForeignKey, OneToOneField,))]
    })
    

    This will do two things:

    1. Add all fields to model admin
    2. Makes sure that there is only a single database call for each related object (instead of one per instance)

    Then to register you model:

    admin.site.register(MyModel, MySpecialAdmin(MyModel))
    

    Note: if you are using a different default model admin, replace 'admin.ModelAdmin' with your admin base class

提交回复
热议问题