• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python utils.get_tag_list函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中tagging.utils.get_tag_list函数的典型用法代码示例。如果您正苦于以下问题:Python get_tag_list函数的具体用法?Python get_tag_list怎么用?Python get_tag_list使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了get_tag_list函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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()
开发者ID:antonioceraso,项目名称:django-tagging,代码行数:31,代码来源:models.py


示例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."
         )
开发者ID:cagerton,项目名称:django-tagging,代码行数:7,代码来源:tests.py


示例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))
开发者ID:Apocalepse,项目名称:django-tagging-ng,代码行数:25,代码来源:core_tests.py


示例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))
开发者ID:Apocalepse,项目名称:django-tagging-ng,代码行数:9,代码来源:core_tests.py


示例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!')
开发者ID:gdub,项目名称:django-tagging,代码行数:10,代码来源:tests.py


示例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!')
开发者ID:crisish,项目名称:blog,代码行数:11,代码来源:tests.py


示例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!")
开发者ID:citadelgrad,项目名称:django-tagging,代码行数:12,代码来源:tests.py


示例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)
开发者ID:Apocalepse,项目名称:django-tagging-ng,代码行数:15,代码来源:core_tests.py


示例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'))
开发者ID:emperorcezar,项目名称:OpenConnect,代码行数:7,代码来源:views.py


示例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,
                  })
开发者ID:mmclaughlin1,项目名称:django-DefectDojo,代码行数:28,代码来源:views.py


示例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)
开发者ID:yrik,项目名称:turmap,代码行数:32,代码来源:models.py


示例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 ''
开发者ID:creativify,项目名称:merengueproj,代码行数:7,代码来源:blocks.py


示例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()
开发者ID:gvidon,项目名称:blombum,代码行数:32,代码来源:managers.py


示例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],
        )
开发者ID:django-tagtools,项目名称:djtt-tagging,代码行数:33,代码来源:models.py


示例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
开发者ID:volgoweb,项目名称:wt,代码行数:59,代码来源:models.py


示例16: delete_story_tags

def delete_story_tags(sender, instance, **kwargs):
    ctype = ContentType.objects.get_for_model(instance)
    tags = get_tag_list(instance.tags)
    TaggedItem._default_manager.filter(content_type__pk=ctype.pk,
                                       object_id=instance.pk,
                                       tag__in=tags).delete()
    for tag in tags:
        if not tag.items.count():
            tag.delete()
开发者ID:aspenlabs,项目名称:blognajd,代码行数:9,代码来源:models.py


示例17: get_related

 def get_related(self, tags, relation_types=['~']):
     """
     Takes a list of tags and returns tags that are related to all of them
     """ 
     tags = get_tag_list(tags)
     result_tags = Tag.objects.all().distinct()
     for tag in tags:
         result_tags = result_tags & tag.get_related(relation_types=relation_types)
     return result_tags
开发者ID:antonioceraso,项目名称:django-tagging,代码行数:9,代码来源:models.py


示例18: clean

 def clean(self, value):
     if self.required and not value:
         raise ValidationError(self.error_messages['required'])
     elif not self.required and not value:
         return []
     try:
         return get_tag_list(value)
     except ValueError:
         raise ValidationError(self.error_messages['list'])
开发者ID:bluezone,项目名称:mirocommunity,代码行数:9,代码来源:forms.py


示例19: get_intersection_by_model

    def get_intersection_by_model(self, queryset_or_model, tags, include_synonyms=True):
        """
        Create a ``QuerySet`` containing instances of the specified
        model associated with *all* of the given list of tags.
        """
        tags = get_tag_list(tags)
        tag_count = len(tags)

        if not tag_count:
            return model._default_manager.none()
        
        # replace the tags with their preferred synonyms if they exist
        temp_tags = []
        for tag in tags:
            try:
                rt = RelatedTag.objects.get(tag=tag, relation_type='=>')
            except RelatedTag.DoesNotExist:
                temp_tags.append(tag)
            else:
                temp_tags.append(rt.related_tag)
        
        # make sure the tags are unique
        tags = list(set(temp_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 all 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
        HAVING COUNT(%(model_pk)s) = %(tag_count)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),
            'tag_count': tag_count,
        }
        print query, ','.join(['%s'] * tag_count), [tag.pk for tag in tags]

        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()
开发者ID:antonioceraso,项目名称:django-tagging,代码行数:53,代码来源:models.py


示例20: testForcingTagsToLowercase

    def testForcingTagsToLowercase(self):
        settings.FORCE_LOWERCASE_TAGS = True

        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))

        Tag.objects.update_tags(dead, None)
        f1 = FormTest.objects.create(tags=u'test3 test2 test1')
        f1.tags = u'TEST5'
        f1.save()
        self.assertListsEqual(get_tag_list('test5'), Tag.objects.get_for_object(f1))
        self.assertEqual(u'test5', f1.tags)
开发者ID:Apocalepse,项目名称:django-tagging-ng,代码行数:22,代码来源:core_tests.py



注:本文中的tagging.utils.get_tag_list函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python utils.parse_tag_input函数代码示例发布时间:2022-05-27
下一篇:
Python utils.get_tag函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap