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
308 views
in Technique[技术] by (71.8m points)

python - Django: apps.get_models() yields models from unittests

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

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

1 Reply

0 votes
by (71.8m points)

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


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

...