问题
In myApp, I have multiple classes in models. I would like to import all of these classes in admin.py and register.
Is it possible without repetition such as
from django.contrib import admin
from .models import (classA,classB, classC)
- Could I import all the items without explicitly referring as done above
- Could I also register all at one time
Thanks
Jeff
回答1:
You can try this :-
import inspect
import models
for name, obj in inspect.getmembers(models):
if inspect.isclass(obj):
admin.site.register(obj)
This will get all the class of models.py and register on admin under loop.
I have not try it but its work same for getting classes on python.
回答2:
you can register all model by using this:
from django.db.models.base import ModelBase from django.contrib import admin import models
for model_name in dir(models):
model = getattr(models, model_name)
if isinstance(model, ModelBase):
admin.site.register(model)
来源:https://stackoverflow.com/questions/45232541/import-and-register-all-classes-from-models-in-admin-django