从orm查询检索的对象中获取字段名称

时间:2013-10-30 15:29:50

标签: python django

我有一个小的Django应用程序,当我用django orm查询我的数据库时,我得到了我的对象列表。 我想要的是查询匹配的db列的名称。 有可能吗?

提前致谢!

results = Verbs.objects.filter(
        Q(fps__icontains = " " + word_name + " ") | Q(fps__endswith = " " + word_name) | Q(fps__startswith = word_name + " ") |
        Q(sps__icontains = " " + word_name + " ") | Q(sps__endswith = " " + word_name) | Q(sps__startswith = word_name + " ") |
        Q(tps__icontains = " " + word_name + " ") | Q(tps__endswith = " " + word_name) | Q(tps__startswith = word_name + " ") |
        Q(fpp__icontains = " " + word_name + " ") | Q(fpp__endswith = " " + word_name) | Q(fpp__startswith = word_name + " ") |
        Q(spp__icontains = " " + word_name + " ") | Q(spp__endswith = " " + word_name) | Q(spp__startswith = word_name + " ") |
        Q(tpp__icontains = " " + word_name + " ") | Q(tpp__endswith = " " + word_name) | Q(tpp__startswith = word_name + " ")
        ).all()

我想要的是匹配查询的字段的名称。例如:fps或fpp ......

1 个答案:

答案 0 :(得分:2)

我认为这就是你想要的 - 对于每个返回的行,它将打印匹配的字段,缩进:

fields = ('fps', 'sps', 'tps', 'fpp', 'spp', 'tpp')
for r in results.values():
    print 'Row with id=%s:' % r['id']
    for f in fields:
        if word_name in str(r[f]):
            print '  Field %s matches' % f

编辑以考虑非字符串值并仅查看所需字段。