Django: apps.get_models() yields models from unittests

℡╲_俬逩灬. 提交于 2019-12-13 08:10:03

问题


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



来源:https://stackoverflow.com/questions/47711724/django-apps-get-models-yields-models-from-unittests

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!