ParticleDecay
2/14/2013 - 8:18 PM

[Django] Basic ad-hoc search for professionals using Q objects.

[Django] Basic ad-hoc search for professionals using Q objects.

def search_publication_professionals(request, firm_slug, template_name='firms/admin/search-publication-professionals.html'):
    keywords = request.GET.get('keywords', None)
    professionals = []

    if keywords:
        keywords_q = Q()

        for keyword in keywords.split():
            keywords_q.add((Q(firm__name__icontains=keyword)), keywords_q.OR)
            keywords_q.add((Q(user__first_name__icontains=keyword)), keywords_q.OR)
            keywords_q.add((Q(user__last_name__icontains=keyword)), keywords_q.OR)
            keywords_q.add((Q(email__icontains=keyword)), keywords_q.OR)

        professionals = Professional.objects.filter(keywords_q)

    return render(request, template_name, locals())