Skip to content

Instantly share code, notes, and snippets.

@lovesh
Last active November 7, 2019 19:37
Show Gist options
  • Save lovesh/6078248 to your computer and use it in GitHub Desktop.
Save lovesh/6078248 to your computer and use it in GitHub Desktop.
django-admin register all models
"""
Here models are in different modules and the models.py imports them from different modules like this
from model1 import * # or the name of models you want to import
from model2 import User
or you might write all your models in models.py
"""
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)
@gardner
Copy link

gardner commented Sep 24, 2018

This works with django 2.1.1

Thank you

@YoniFeng
Copy link

YoniFeng commented Oct 2, 2018

Not sure why, but despite admin.py being in the app's folder, import models isn't found. (Using django 2.1.2, although I don't see how that could have any affect).
I had to to import app_name.models.

This might be some weird relative/reference issue in my specific setup (although my setup is super vanilla).
In any case if anybody encounters the same issue, there's your answer ^^
Also if somebody knows why I can't resolve the plain import models, please enlighten me :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment