从标签数量中排除一些帖子

时间:2018-02-01 21:41:30

标签: django django-taggit django-aggregation

我使用django-taggit来管理我的代码。 我想要包含一个使用过的标签列表,并指出每个标签的使用次数。为此,我使用taggit_templatetags2,但我可以避免。

我的models.py

from taggit.managers import TaggableManager

class Post(models.Model):
    ...
    tags = TaggableManager(blank=True)

我的template.html

{% load taggit_templatetags2_tags %}

  {% get_taglist as tags for 'blog.post' %}

  {% for tag in tags %}
    {% if tag.slug != 'draft' and tag.slug != 'retired' %}
      <h4 style="text-align:center"><a href="{% url 'blog:post_list_by_tag' tag.slug %}">
        {{ tag }} ({{ tag.num_times }}) </a></h4>
    {% endif %}
  {% endfor %}

但我想从计票中排除草稿帖子和退休帖子的所有标签。我不想仅仅排除标签&#39; draft&#39;和退休的&#39; (我已经这样做了)但是这些帖子可以拥有的其他标签。我怎么能这样做?

例如,我有两个帖子。第一个只有标签&#39; dog&#39;。第二个有标签&#39; dog&#39;并且&#39;草稿&#39;。它是一个草案,一个尚未公布的帖子。

我的代码会给:dog(2)因为它会计算所有帖子的标签。当用户点击“狗”时它将显示一个页面,其中所有已发布的帖子都带有狗牌,所以在我们的案例中有一个帖子,因为第二个帖子没有发布。用户会问自己:有两个狗帖,第二个在哪里?这不好。此外,我不想暗示即将发布的帖子的论点。

可能我不得不弄乱taggit_templatetags2代码...

说实话,我很难理解这段代码,我认为最好不要直接更改原始代码,否则在第一次更新时我的代码就会丢失。

这里有一些taggit_templatetags2的代码:

@register.tag
class GetTagList(TaggitBaseTag):
    name = 'get_taglist'

    def get_value(self, context, varname, forvar, limit=settings.LIMIT, order_by=settings.TAG_LIST_ORDER_BY):
        # TODO: remove default value for limit, report a bug in the application
        # django-classy-tags, the default value does not work
        queryset = get_queryset(
            forvar,
            settings.TAGGED_ITEM_MODEL,
            settings.TAG_MODEL)
        queryset = queryset.order_by(order_by)
        context[varname] = queryset
        if limit:
            queryset = queryset[:limit]
        return ''

def get_queryset(forvar, taggeditem_model, tag_model):
    through_opts = taggeditem_model._meta
    count_field = (
        "%s_%s_items" % (
            through_opts.app_label,
            through_opts.object_name)).lower()

    if forvar is None:
        # get all tags
        queryset = tag_model.objects.all()
    else:
        # extract app label and model name
        beginning, applabel, model = None, None, None
        try:
            beginning, applabel, model = forvar.rsplit('.', 2)
        except ValueError:
            try:
                applabel, model = forvar.rsplit('.', 1)
            except ValueError:
                applabel = forvar
        applabel = applabel.lower()

        # filter tagged items
        if model is None:
            # Get tags for a whole app
            queryset = taggeditem_model.objects.filter(
                content_type__app_label=applabel)
            tag_ids = queryset.values_list('tag_id', flat=True)
            queryset = tag_model.objects.filter(id__in=tag_ids)
        else:
            # Get tags for a model
            model = model.lower()
            if ":" in model:
                model, manager_attr = model.split(":", 1)
            else:
                manager_attr = "tags"
            model_class = get_model(applabel, model)
            if not model_class:
                raise Exception(
                    'Not found such a model "%s" in the application "%s"' %
                    (model, applabel))
            manager = getattr(model_class, manager_attr)
            queryset = manager.all()
            through_opts = manager.through._meta
            count_field = ("%s_%s_items" % (through_opts.app_label,
                                            through_opts.object_name)).lower()

    if count_field is None:
        # Retain compatibility with older versions of Django taggit
        # a version check (for example taggit.VERSION <= (0,8,0)) does NOT
        # work because of the version (0,8,0) of the current dev version of
        # django-taggit
        try:
            return queryset.annotate(
                num_times=Count(settings.TAG_FIELD_RELATED_NAME))
        except FieldError:
            return queryset.annotate(
                num_times=Count('taggit_taggeditem_items'))
    else:
        return queryset.annotate(num_times=Count(count_field))

其中:

queryset = manager.all()列出了所有标签

count_field是一个字符串:taggit_taggeditem_items

queryset.annotate(num_times=Count(count_field))是带有额外字段num_times的查询集,

2 个答案:

答案 0 :(得分:0)

  • 如果您想有效地从查询集中排除项目,请尝试在查询集上使用排除方法:

    queryset.exclude(slug__in = [&#39; draft&#39;,&#39;退休&#39;])

  • 您还可以尝试使用方法计算代码的出现次数。如果我理解正确,请尝试:

    queryset.values(&#39; ID&#39)。注释(NUM_TIMES =计数(count_field))

答案 1 :(得分:0)

所以,在这里我做了什么,没有taggit_template_tags2,可能会被优化,欢迎你!

我的model.py

class Post(models.Model):
    ...
    tags = TaggableManager(blank=True)

我的views.py

...
#filter the posts that I want to count
tag_selected = get_object_or_404(Tag, slug='ritired')
posts = Post.objects.filter(published_date__lte=timezone.now()).exclude(tags__in=[tag_selected])
#create a dict with all the tags and value=0
tag_dict = {}
tags=Post.tags.all()
for tag in tags:
    tag_dict[tag]=0
#count the tags in the post and update the dict
for post in posts:
    post_tag=post.tags.all()
    for tag in post_tag:
        tag_dict[tag]+=1
#delete the key with value=0
tag_dict = {key: value for key, value in tag_dict.items() if value != 0}
#pass the dict to the template
context_dict={}
context_dict['tag_dict']=tag_dict
return render(request, 'blog/post_list.html', context_dict)

我的template.html

  {% for key, value in tag_dict.items %}
    <h4 style="text-align:center"><a href="{% url 'blog:post_list_by_tag' key.slug %}">
      {{ key }} ({{ value }})
    </h4>
  {% endfor %}

快速而简单!