How can i get all models in django 1.8
Asked Answered
C

1

19

I am using this code in my admin.py

from django.db.models import get_models, get_app

for model in get_models(get_app('myapp')):
    admin.site.register(model)

But i get warning that get_models is deprecated

How can i do that in django 1.8

Chauffeur answered 20/4, 2015 at 3:41 Comment(3)
It's a warning. Is it actively prohibiting you from getting the models result? I wouldn't expect a warning to do that except to inform you that this approach is going away in a future Django version.Dewie
@Dewie it says that it will be removed in 1.9 . i thought it would be better to use the latest stuff rather than chnage it in few months againChauffeur
This is a totally rational reason to want to migrate; however, the way your question reads is that you were having trouble getting the values back from this command. My concern was that it was prohibiting you from getting any information back, which would have been counter-intuitive.Dewie
P
39

This should work,

from django.apps import apps
apps.get_models()

The get_models method returns a list of all installed models. You can also pass three keyword arguments include_auto_created, include_deferred and include_swapped.

If you want to get the models for a specific app, you can do something like this.

from django.apps import apps
myapp = apps.get_app_config('myapp')
myapp.models

This will return an OrderedDict instance of the models for that app.

Polymyxin answered 20/4, 2015 at 3:57 Comment(2)
I tried that to register admin site like admin.site.register(myapp.models[0]) but i get this 'str' object has no attribute '_meta'Chauffeur
It's because it returns an OrderedDict instance. You want to call myapp.models.values().Polymyxin

© 2022 - 2024 — McMap. All rights reserved.