问题
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):
Create manually, a list of all your application names as strings:
my_apps=['my_app_1', 'my_app_2', ...]
(First Option), use
get_app_config
andget_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
(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