Django:apps.get_models()从单元测试产生模型 [英] Django: apps.get_models() yields models from unittests

查看:105
本文介绍了Django:apps.get_models()从单元测试产生模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我调用此django方法,则在测试中会产生许多未安装的模型.
这些模型来自其他应用程序的测试代码.

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.

例如,当我使用apps.get_models()时,我从django包多态测试代码中获得了MROBase1.

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.

注意::我使用的是Django 1.10

NB: I use Django 1.10

推荐答案

您需要将模型与应用程序隔离:

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

  1. 手动创建所有应用程序名称的列表作为字符串:my_apps=['my_app_1', 'my_app_2', ...]

(首选),请使用get_app_configget_models方法:

from django.apps import apps

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

您最终将得到一个'app_name': list_of_models

(第二个选项),请使用all_models[<app_name>]属性:

from django.apps import apps

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

您最终将得到一个'app_name': OrderedDict_of_models

这篇关于Django:apps.get_models()从单元测试产生模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆