2
\$\begingroup\$

I am currently hooking a large database up to a django site and want to populate the admin page with a number of models. I am using inspect to get a list of classes from each model file (one file per database in MySQL) and then registering them by name.

from django.contrib import admin
import inspect
from .models import auth

# Auth
for pair in inspect.getmembers(auth):
    # returns a tuple with the class name and ref
    model = tuple[1]
    if tuple[0][0] is not "_" and tuple[0][0].upper() == tuple[0][0]:
        # it doesnt start with _ and does start with an uppercase
        admin.site.register(model)

Is there anything wrong with this code? Is getting class references like this bad practice? It just seems to easy to be true.

\$\endgroup\$
5
\$\begingroup\$

The usual "django" way of doing this - is to use get_app_config() function to get the AppConfig instance, then call .get_models() method:

from django.apps import apps

app = apps.get_app_config('auth')

for model in app.get_models(): 
    admin.site.register(model)
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.