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)
Comments
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.
#