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

Dhia
  • 10,119
  • 11
  • 58
  • 69
user3214546
  • 6,523
  • 13
  • 51
  • 98
  • 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. – Makoto Apr 20 '15 at 03:54
  • 3
    @Makoto 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 again – user3214546 Apr 20 '15 at 04:41
  • 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. – Makoto Apr 20 '15 at 04:43

1 Answers1

38

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.

Rod Xavier
  • 3,983
  • 1
  • 29
  • 41
  • I tried that to register admin site like `admin.site.register(myapp.models[0])` but i get this `'str' object has no attribute '_meta'` – user3214546 Apr 20 '15 at 04:38
  • 1
    It's because it returns an `OrderedDict` instance. You want to call `myapp.models.values()`. – Rod Xavier Apr 20 '15 at 04:40