[Django]-Is it possible to get a list of imported things from a module in Python?

3👍

import inspect
import test_module # module to be inspected

for name, data in inspect.getmembers(test_module):
    if name.startswith("__"):
        continue
    if 'class' in str(data):
        print(name)

0👍

One solution I just thought could be to make my own function that imports from .models and registers the elements, like

def import_and_register(arg_list):
    for a in arg_list:
        from .models import a
        admin.site.register(a)

But can I do this with a builtin feature? Are there any major cons to this approach?

0👍

I don’t believe there is, but perhaps to save yourself from typing remember the names, just store them in a collection.

from .models import Food, Drink, Topping

MY_FANCY_MODELS = Food, Drink, Topping

for m in MY_FANCY_MODELS:
    admin.site.register(m)

👤bsoist

0👍

I feel, you can do it like this –

import models
for i in dir(models):
    if isinstance(i, type):
        admin.site.register(i)

dir(models) retrieves all the attributes of module.

Leave a comment