我如何使用变量作为Django模型

时间:2019-11-20 08:23:15

标签: django django-rest-framework

我想使用此功能从数据库中获取列表:

def get_db_list(IN_DICT, **kwargs):
    off = kwargs.get('off', None)
    limit = kwargs.get('limit', None)
    Keyword = {}
    Keyword[IN_DICT['ITEM']] = IN_DICT['TYPE']
    if off == None and limit == None:
        LIST = IN_DICT['TABLE'].objects.filter(**Keyword)
    else:
        LIST = IN_DICT['TABLE'].objects.filter(**Keyword)[off:limit]
    return LIST

现在我的问题是,IN_DICT ['TABLE']作为字符串传递:

>>> type(Host_Table)
<class 'django.db.models.base.ModelBase'>
>>> IN_DICT['TABLE']
'Host_Table'
>>> type(IN_DICT['TABLE'])
<class 'str'>

我该如何更改类型?

此示例仅从该表中提取正确的查询:

def get_db_list(IN_DICT, **kwargs):
    off = kwargs.get('off', None)
    limit = kwargs.get('limit', None)
    Keyword = {}
    Keyword[IN_DICT['ITEM']] = IN_DICT['TYPE']
    if off == None and limit == None:
        LIST = Host_Table.objects.filter(**Keyword)
    else:
        LIST = Host_Table.objects.filter(**Keyword)[off:limit]
    return LIST

解决方案:

from django.apps import apps

def get_db_list(IN_DICT, **kwargs):
    off = kwargs.get('off', None)
    limit = kwargs.get('limit', None)
    Keyword = {}
    Keyword[IN_DICT['ITEM']] = IN_DICT['TYPE']
    Table = apps.get_model('vulture', IN_DICT['TABLE'])
    if off == None and limit == None:
        LIST = Table.objects.filter(**Keyword)
    else:
        LIST = Table.objects.filter(**Keyword)[off:limit]
    return LIST

0 个答案:

没有答案