Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

If I call this django method, in a test, it yields a lot of models which are not installed.
These models are from other apps test code.

For example, when iI use apps.get_models() I get MROBase1 from the django package polymorphic test code.

=> I want get all models which have a table in the database. In above question I got a model which exists just for testing, which is not on the database.

NB: I use Django 1.10

See Question&Answers more detail:os

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

1 Answer

You need to isolate the models from your application(s):

  1. Create manually, a list of all your application names as strings: my_apps=['my_app_1', 'my_app_2', ...]

  2. (First Option), use get_app_config and get_models methods:

    from django.apps import apps
    
    my_app_models = {
        name: list(apps.get_app_config(name).get_models()) for name in my_apps
    }
    

    You will end up with a dictionary of 'app_name': list_of_models

  3. (Second Option), use all_models[<app_name>] attribute:

    from django.apps import apps
    
    my_app_models = {name: apps.all_models[name] for name in my_apps}
    

    You will end up with a dictionary of 'app_name': OrderedDict_of_models


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...