ampad

Digitale Lösungen

Yesterday I had to quickly search for a certain string in all the models of a django application. The following snippet will do just that. Mind you, this is just a quick and dirty way to get results in the shell, I wouldn't suggest building a search feature based on that.

import django.apps
from django.db.models import Q


def search_all_fields(term, lookups=('contains', 'exact')):
    results = {}
    for model in django.apps.apps.get_models():
        opts = model._meta
        q = Q()
        for field in opts.fields:
            for lookup in lookups:
                q_test = Q(**{'{}__{}'.format(field.name, lookup): term})
                # we execute the query here because some field types will error
                # out only when the query is execeuted
                try:
                    model._default_manager.filter(q_test).exists()
                    q |= q_test
                    break
                except:
                    pass

        label = "{}_{}".format(opts.app_label, opts.model_name)
        results[label] = model._default_manager.filter(q)
    return results