本文整理汇总了Python中tagging.utils.get_tag_list函数的典型用法代码示例。如果您正苦于以下问题:Python get_tag_list函数的具体用法?Python get_tag_list怎么用?Python get_tag_list使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了get_tag_list函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: relate
def relate(self, tags, relation_type='~', related_tags=[], force_create=False):
'''
Relates each tag in a list of tags with each tag in a list of related_tags
with the given relation type. Tag lists can be Tag instances or strings.
Relations are created symmetrically. If force_create = True, tags are
created from string if they do not already exist. If just a list of tags are
given, it calls relate_all() to relate them with each other using '~' relation.
Updates existing relations if needed.
'''
#TODO: WTF
tags = get_tag_list(tags)
if related_tags == []:
self.relate_all(tags)
else:
related_tags = get_tag_list(related_tags)
for tag in tags:
tag = get_tag(tag)
if tag and tag.is_valid:
for related_tag in related_tags:
related_tag = get_tag(related_tag)
if related_tag and related_tag.is_valid:
if tag != related_tag:
rel, c = RelatedTag.objects.get_or_create(tag=tag, related_tag=related_tag,
defaults={'relation_type': relation_type,
'count': 1})
if not c:
rel.count += 1
# check if the existing relation is correct
if rel.relation_type != relation_type:
rel.relation_type = relation_type
rel.save()
示例2: test_with_invalid_input_mix_of_string_and_instance
def test_with_invalid_input_mix_of_string_and_instance(self):
try:
get_tag_list(["cheese", self.toast])
except ValueError, ve:
self.assertEquals(
str(ve), "If a list or tuple of tags is provided, they must all be tag names, Tag objects or Tag ids."
)
示例3: testBasicTagging
def testBasicTagging(self):
dead = Parrot.objects.create(state='dead')
Tag.objects.update_tags(dead, 'foo,bar,"ter"')
self.assertListsEqual(get_tag_list('bar foo ter'), Tag.objects.get_for_object(dead))
Tag.objects.update_tags(dead, '"foo" bar "baz"')
self.assertListsEqual(get_tag_list('bar baz foo'), Tag.objects.get_for_object(dead))
Tag.objects.add_tag(dead, 'foo')
self.assertListsEqual(get_tag_list('bar baz foo'), Tag.objects.get_for_object(dead))
Tag.objects.add_tag(dead, 'zip')
self.assertListsEqual(get_tag_list('bar baz foo zip'), Tag.objects.get_for_object(dead))
self.assertRaises(AttributeError, Tag.objects.add_tag, dead, ' ')
self.assertRaises(AttributeError, Tag.objects.add_tag, dead, 'one two')
Tag.objects.update_tags(dead, 'ŠĐĆŽćžšđ')
self.assertEqual(
'[<Tag: \xc5\xa0\xc4\x90\xc4\x86\xc5\xbd\xc4\x87\xc5\xbe\xc5\xa1\xc4\x91>]',
repr(Tag.objects.get_for_object(dead)))
Tag.objects.update_tags(dead, None)
self.assertListsEqual([], Tag.objects.get_for_object(dead))
示例4: testUsingAModelsTagField
def testUsingAModelsTagField(self):
f1 = FormTest.objects.create(tags=u'test3 test2 test1')
self.assertListsEqual(get_tag_list('test1 test2 test3'), Tag.objects.get_for_object(f1))
f1.tags = u'test4'
f1.save()
self.assertListsEqual(get_tag_list('test4'), Tag.objects.get_for_object(f1))
f1.tags = ''
f1.save()
self.assertListsEqual([], Tag.objects.get_for_object(f1))
示例5: test_with_invalid_input
def test_with_invalid_input(self):
try:
get_tag_list(29)
except ValueError as ve:
self.assertEqual(str(ve), 'The tag input given was invalid.')
except Exception as e:
raise self.failureException('the wrong type of exception was raised: type [%s] value [%s]' %\
(str(type(e)), str(e)))
else:
raise self.failureException('a ValueError exception was supposed to be raised!')
示例6: test_with_invalid_input_mix_of_string_and_instance
def test_with_invalid_input_mix_of_string_and_instance(self):
try:
get_tag_list(['cheese', self.toast])
except ValueError as ve:
self.assertEqual(str(ve),
'If a list or tuple of tags is provided, they must all be tag names, Tag objects or Tag ids.')
except Exception as e:
raise self.failureException('the wrong type of exception was raised: type [%s] value [%]' %\
(str(type(e)), str(e)))
else:
raise self.failureException('a ValueError exception was supposed to be raised!')
示例7: test_with_invalid_input
def test_with_invalid_input(self):
try:
get_tag_list(29)
except ValueError as ve:
self.assertEqual(str(ve), "The tag input given was invalid.")
except Exception as e:
print("--", e)
raise self.failureException(
"the wrong type of exception was raised: " "type [%s] value [%s]" % (str(type(e)), str(e))
)
else:
raise self.failureException("a ValueError exception was supposed to be raised!")
示例8: testNormalisedTagListInput
def testNormalisedTagListInput(self):
cheese = Tag.objects.create(name='cheese')
toast = Tag.objects.create(name='toast')
self.assertListsEqual([cheese], get_tag_list(cheese))
self.assertListsEqual([cheese, toast], get_tag_list('cheese toast'))
self.assertListsEqual([cheese, toast], get_tag_list('cheese,toast'))
self.assertListsEqual([], get_tag_list([]))
self.assertListsEqual([cheese, toast], get_tag_list(['cheese', 'toast']))
self.assertListsEqual([cheese, toast], get_tag_list([cheese.id, toast.id]))
self.assertListsEqual([cheese, toast], get_tag_list(['cheese', 'toast', 'ŠĐĆŽćžšđ']))
self.assertListsEqual([cheese, toast], get_tag_list([cheese, toast]))
self.assertEqual((cheese, toast), get_tag_list((cheese, toast)))
self.assertListsEqual([cheese, toast], get_tag_list(Tag.objects.filter(name__in=['cheese', 'toast'])))
self.assertRaises(ValueError, get_tag_list, ['cheese', toast])
self.assertRaises(ValueError, get_tag_list, 29)
示例9: tag_search
def tag_search(request, tag, page=1, paginate_by=10, rtemplate="contacts/tag_results.html"):
qstagquery = tagutils.get_tag_list(tag)
taggedcontacts = TaggedItem.objects.get_by_model(Contact, [tag.name for tag in qstagquery])
qscontacts = Contact.objects.filter(id__in = [c.id for c in taggedcontacts])
request.session['searchresults'] = qscontacts
return HttpResponseRedirect(reverse('contacts-searchresults'))
示例10: edit_object
def edit_object(request, pid, ttid):
object = Objects.objects.get(pk=ttid)
if request.method == 'POST':
tform = ObjectSettingsForm(request.POST, instance=object)
if tform.is_valid():
tform.save()
tags = request.POST.getlist('tags')
t = ", ".join(tags)
object.tags = t
messages.add_message(request,
messages.SUCCESS,
'Tool Product Configuration Successfully Updated.',
extra_tags='alert-success')
return HttpResponseRedirect(reverse('view_objects', args=(pid,)))
else:
tform = ObjectSettingsForm(instance=object,
initial={'tags': get_tag_list(Tag.objects.get_for_object(object))})
tform.initial['tags'] = [tag.name for tag in object.tags]
add_breadcrumb(title="Edit Tracked Files", top_level=False, request=request)
return render(request,
'dojo/edit_object.html',
{
'tform': tform,
})
示例11: related_for_model
def related_for_model(self, tags, model, counts=False, min_count=None, label=None):
"""
Obtain a list of tags related to a given list of tags - that
is, other tags used by items which have all the given tags.
If ``counts`` is True, a ``count`` attribute will be added to
each tag, indicating the number of items which have it in
addition to the given list of tags.
If ``min_count`` is given, only tags which have a ``count``
greater than or equal to ``min_count`` will be returned.
Passing a value for ``min_count`` implies ``counts=True``.
"""
## Nonrel requires two (maybe three) queries and in-memory aggregation and sorting
## (1) grab all of the object_ids that point to the specified tags, for the model
object_ids = TaggedItem.objects._get_intersection_object_ids(model, tags)
## (2) grab all of the TaggedItems that point to the same objects
content_type = ContentType.objects.get_for_model(model)
related = TaggedItem._default_manager.filter(object_id__in=object_ids,
content_type=content_type)
## if there are no related TaggedItems at all, then there are no related tags
if len(list(related)) == 0: ## TODO: django-nonrel len() bug
return []
## (3) Simulate SQL aggregation in memory, and exclude the original tags.
exclude_ids = set()
for tag in get_tag_list(tags): #this may, or may not, execute an additional query
exclude_ids.add(tag.id)
return self._package_and_sort(related, counts, min_count, exclude_ids)
示例12: render
def render(self, request, place, content, context, *args, **kwargs):
if content and content.tags:
content_tags = [i.name for i in get_tag_list(content.tags)]
taglist = ITag.objects.filter(name__in=content_tags)
return self.render_block(request, template_name='itags/blocks/content_tags.html',
context={'taglist': taglist})
return ''
示例13: get_union_by_model
def get_union_by_model(self, queryset_or_model, tags):
"""
Create a ``QuerySet`` containing instances of the specified
model associated with *any* of the given list of tags.
"""
tags = get_tag_list(tags)
tag_count = len(tags)
queryset, model = get_queryset_and_model(queryset_or_model)
model_table = qn(model._meta.db_table)
# This query selects the ids of all objects which have any of
# the given tags.
query = """
SELECT %(model_pk)s
FROM %(model)s, %(tagged_item)s
WHERE %(tagged_item)s.content_type_id = %(content_type_id)s
AND %(tagged_item)s.tag_id IN (%(tag_id_placeholders)s)
AND %(model_pk)s = %(tagged_item)s.object_id
GROUP BY %(model_pk)s""" % {
'model_pk': '%s.%s' % (model_table, qn(model._meta.pk.column)),
'model': model_table,
'tagged_item': qn(self.model._meta.db_table),
'content_type_id': ContentType.objects.get_for_model(model).pk,
'tag_id_placeholders': ','.join(['%s'] * tag_count),
}
cursor = connection.cursor()
cursor.execute(query, [tag.pk for tag in tags])
object_ids = [row[0] for row in cursor.fetchall()]
if len(object_ids) > 0:
return queryset.filter(pk__in=object_ids)
else:
return model._default_manager.none()
示例14: get_by_model
def get_by_model(self, queryset_or_model, tags):
"""
Create a ``QuerySet`` containing instances of the specified
model associated with a given tag or list of tags.
"""
tags = get_tag_list(tags)
tag_count = len(tags)
if tag_count == 0:
# No existing tags were given
queryset, model = get_queryset_and_model(queryset_or_model)
return model._default_manager.none()
elif tag_count == 1:
# Optimisation for single tag - fall through to the simpler
# query below.
tag = tags[0]
else:
return self.get_intersection_by_model(queryset_or_model, tags)
queryset, model = get_queryset_and_model(queryset_or_model)
content_type = ContentType.objects.get_for_model(model)
opts = self.model._meta
tagged_item_table = qn(opts.db_table)
return queryset.extra(
tables=[opts.db_table],
where=[
'%s.content_type_id = %%s' % tagged_item_table,
'%s.tag_id = %%s' % tagged_item_table,
'%s.%s = %s.object_id' % (qn(model._meta.db_table),
qn(model._meta.pk.column),
tagged_item_table)
],
params=[content_type.pk, tag.pk],
)
示例15: related_for_model
def related_for_model(self, tags, model, counts=False, min_count=None,
wildcard=None, default_namespace=None):
"""
Obtain a list of tags related to a given list of tags - that
is, other tags used by items which have all the given tags.
If ``counts`` is True, a ``count`` attribute will be added to
each tag, indicating the number of items which have it in
addition to the given list of tags.
If ``min_count`` is given, only tags which have a ``count``
greater than or equal to ``min_count`` will be returned.
Passing a value for ``min_count`` implies ``counts=True``.
"""
if min_count is not None: counts = True
tags = get_tag_list(tags,
wildcard=wildcard, default_namespace=default_namespace)
tag_count = len(tags)
tagged_item_table = qn(TaggedItem._meta.db_table)
query = """
SELECT %(tag)s.id, %(tag)s.namespace, %(tag)s.name, %(tag)s.value%(count_sql)s
FROM %(tagged_item)s INNER JOIN %(tag)s ON %(tagged_item)s.tag_id = %(tag)s.id
WHERE %(tagged_item)s.content_type_id = %(content_type_id)s
AND %(tagged_item)s.object_id IN
(
SELECT %(tagged_item)s.object_id
FROM %(tagged_item)s, %(tag)s
WHERE %(tagged_item)s.content_type_id = %(content_type_id)s
AND %(tag)s.id = %(tagged_item)s.tag_id
AND %(tag)s.id IN (%(tag_id_placeholders)s)
GROUP BY %(tagged_item)s.object_id
HAVING COUNT(%(tagged_item)s.object_id) = %(tag_count)s
)
AND %(tag)s.id NOT IN (%(tag_id_placeholders)s)
GROUP BY %(tag)s.id, %(tag)s.namespace, %(tag)s.name, %(tag)s.value
%(min_count_sql)s
ORDER BY %(tag)s.name ASC""" % {
'tag': qn(self.model._meta.db_table),
'count_sql': counts and ', COUNT(%s.object_id)' % tagged_item_table or '',
'tagged_item': tagged_item_table,
'content_type_id': ContentType.objects.get_for_model(model).pk,
'tag_id_placeholders': ','.join(['%s'] * tag_count),
'tag_count': tag_count,
'min_count_sql': min_count is not None and ('HAVING COUNT(%s.object_id) >= %%s' % tagged_item_table) or '',
}
params = [tag.pk for tag in tags] * 2
if min_count is not None:
params.append(min_count)
cursor = connection.cursor()
cursor.execute(query, params)
related = []
for row in cursor.fetchall():
tag = self.model(*row[:4])
if counts is True:
tag.count = row[4]
related.append(tag)
return related