-->

Django: apps.get_models() yields models from unitt

2019-09-21 01:41发布

问题:

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

回答1:

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



回答2:

apps.get_models() will return all installed models, if you want to restrict the set of installed apps used by get_app_config[s] you can use set_available_apps:

from django.apps import apps
myapp = apps.set_available_apps(list_of_available_apps)


回答3:

See this SO post.

apps.get_models() will return all installed models. If you are looking for a list of models for a specific app, do the following:

from django.apps import apps
myapp = apps.get_app_config('myapp')
myapp.models #returns an OrderedDict

Also, for reference, here's the source of get_models() to see how it works