当前位置: 动力学知识库 > 问答 > 编程问答 >

django - How to register multiple models with the admin?

问题描述:

If I want to register my models with the admin I have to do this like this:

#admin.py

admin.site.register(models.About)

But with multiple models you can't do something like this:

models = (models.Project, models.Client, models.About)

for m in models:

admin.site.register(m)

First of all: why not!? Secondly: imagine one has a lot of models which all should be accessible from the admin interface. How do you do that in a generic way?

网友答案:

admin.site.register has this definition in library

def register(self, model_or_iterable, admin_class=None, **options):

so models to be registered can be a single model or iterable object so

just use this :

myModels = [models.Project, models.Client, models.About]  # iterable list

admin.site.register(myModels)

I tested this in my site and works perfectly fyn.

网友答案:

With respect to the recent release of Django 1.7, you can use the django.contrib.admin.register decorator to register multiple models that using the same admin class.

from django.contrib import admin
from .models import Project, Client, About

@admin.register(Project, Client, About)
class DefaultAdmin(admin.ModelAdmin):
    pass

Update

Consider making a simple call instead of declaring a class

网友答案:

Based on the snippet here, what I usually do is have the following code in my admin.py

from django.db.models import get_models, get_app
from django.contrib import admin
from django.contrib.admin.sites import AlreadyRegistered

def autoregister(*app_list):
    for app_name in app_list:
        app_models = get_app(app_name)
        for model in get_models(app_models):
            try:
                admin.site.register(model)
            except AlreadyRegistered:
                pass

autoregister('myapp')
网友答案:
# File: admin.py
from django.contrib import admin
from .models import Project, Client, About

admin.register(Project, Client, About)(admin.ModelAdmin)
分享给朋友:
您可能感兴趣的文章:
随机阅读: