Hi everyone !
I’m just wondering how can I refactor this code :
from django.contrib import admin
from .models import *
# Register your models here.
models_list = [Forum, Topic, Post]
admin.site.register(models_list)
Indeed I would like to directly import every models from .models as a list. Because actually, if I add another model to .models, I will have to add it to models_list too…
Does someone have a clue ?
Thanks
Hi @valenciano8
Individually registering the models is normal. Sometimes you might add a model that you don’t want to individually expose to the admin for security reasons, or parent models that aren’t relevant to display.
That said as a quick start, you can auto-register all model subclasses defined in your app’s models
module with a list comprehension like (untested):
from django.db.models import Model
from myapp import models
admin.site.register([obj for obj in models.__dict__.values() if issubclass(models, Model)])
This uses the module’s __dict__
to retrieve all its attributes that are subclasses of Django’s base Model
class.
Not that I recommend this (although I use this regularly ) but django.apps
from django.apps import apps
makes available:
apps.all_models['app_name']
returns a dict with the values being the models belonging to that app.
Thus:
admin.site.register(apps.all_models['app_name'].values())
will register all models in an app.