Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
197 views
in Technique[技术] by (71.8m points)

python - How do I retrieve a Django model class dynamically?

Without having the full module path of a Django model, is it possible to do something like:

model = 'User' [in Django namespace]
model.objects.all()

...as opposed to:

User.objects.all().

EDIT: I am trying to make this call based on command-line input. Is it possible to avoid the import statement, e.g.,

model = django.authx.models.User

Without Django returning the error:

"global name django is not defined."
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think you're looking for this:

from django.db.models.loading import get_model
model = get_model('app_name', 'model_name')

There are other methods, of course, but this is the way I'd handle it if you don't know what models file you need to import into your namespace. (Note there's really no way to safely get a model without first knowing what app it belongs to. Look at the source code to loading.py if you want to test your luck at iterating over all the apps' models.)

Update for Django 1.7+: According to Django's deprecation timeline, django.db.models.loading has been deprecated in Django 1.7 and will be removed in Django 1.9. As pointed out in Alasdair's answer, In Django 1.7+, there is an applications registry. You can use the apps.get_model method to dynamically get a model:

from django.apps import apps
MyModel = apps.get_model('app_label', 'MyModel')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...