View to retrieve objects meeting a complex tag query

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import re
from tagging.models import Tag, TaggedItem
from django.db.models import Q, get_model

def tag_view(request, 
             tag_expression, 
             app_name = 'pubman',
             model_name='article', 
             view=article_list_view,
             html_template='pubman/tag.html'):


    model_filter = TaggedItem.objects.all().filter(content_type__model=model_name)
    
    search_string = '\'[\w\s]+\'|\"[\w\s]+\"|[\w\s]+|&|\||\(|\)|-'    
    parse_string = re.findall(search_string, tag_expression)
    
    print parse_string
    
    querystring = ""
     
    for token in parse_string:
        if token in ['&', '|','-', '(',')']:
            querystring +=  ' ' + token + ' '
        elif token == 'ALL':
            querystring += ' set([i.id for i in get_model("' +\
                app_name + '", "' +\
                model_name + '")'+ '.objects.all()])'            
        else:
            token = token.replace('"','')
            token = token.replace("'","")            
            querystring += ' set([i.object_id for i in '+\
                'model_filter.filter(tag__name="' + token + '")])'

    print 'Query: ', querystring

    try:                
        instances = eval(querystring)
    except:
        # This is the fallback when there's an error in the expression.
        # A better way might be to raise Http404.
        instances = model_filter.filter(tag__name=tag_expression)

    object_list = get_model(app_name, model_name).\
        objects.all().filter(id__in=instances)
        
    return view(request, object_list, html_template)

More like this

  1. keywords arguments parser for custom template tags by bruno 5 years, 2 months ago
  2. Effective content caching for mass-load site using redirect feature by nnseva 2 years, 9 months ago
  3. A GET string modifier templatetag by cogat 5 years, 4 months ago
  4. RelatedMixin for Details and Updates with Related Object Lists by christhekeele 1 year, 11 months ago
  5. DebugMiddleware footer with links to quick open file/line# in TextMate on local machine by felix_the_third 4 years, 3 months ago

Comments

nathangeffen (on December 22, 2010):

Apologies, the first version I uploaded was not generic. But I've corrected it and now it should be. I've also improved the description.

#

(Forgotten your password?)