问题描述
我正在使用 django-taggit 来管理我的标签.我想包括一个已使用标签的列表,其中包含每个标签已被使用多少次的指示.为此,我正在使用 taggit_templatetags2 ,但我可以避免.
I'm using django-taggit to manage my tag.I want to include a list of used tags with the indication of how many times each of them has been used. To do so I'm using taggit_templatetags2 but I can avoid.
我的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 %}
但是,我想从草稿中排除所有帖子标签和退休帖子的标签.我不想仅排除草稿"和退休"标签(我已经这样做了),甚至不包括此类帖子可以包含的其他标签.我该怎么办?
But I want to exclude from the count all the tags of the draft posts and of the retired posts. I do not want just to exclude the tags 'draft' and 'retired' (I'm already doing that) but even the other tags that such posts can have. How can I do that?
例如,我有两个帖子.第一个只有标签"dog".第二个具有标签"dog"和"draft".这是草稿,尚未发布的帖子.
For example I have two posts. The first one have only the tag 'dog'. The second one have the tags 'dog' and 'draft'. It's a draft, a post not yet publicated.
我的代码将给出:dog(2),因为它计算了所有帖子的标签.当用户单击狗"时,将出现一个页面,其中所有已发布的帖子都带有dog标签,因此在本例中,因为第二个帖子未发布,所以它是一个帖子.使用者会问自己:有两个狗桩,第二个在哪里?不好另外,我也不想暗示即将发布的帖子的论点.
My code would give: dog (2) because it count the tags of all the posts. When a user will click on 'dog' it will appears a page with all the published post with a dog tag, so in our case one post because the second one isn't published. The user will ask himself: there are two dog posts, where is the second one? This isn't good. Also I don't want to hint the argument of the soon-to-be published posts.
可能我必须弄乱taggit_templatetags2
代码...
Probably I have to mess with the taggit_templatetags2
code...
说实话,我很难理解这段代码,我认为最好不要直接更改原始代码,否则在第一次更新时我的代码会丢失.
To be honest it's difficoult for me to understand this code, also I think it would be better to don't change directly the original code or at the first update my code will be lost.
以下是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
推荐答案
所以,在这里,我做的没有taggit_template_tags2的东西,很可能会被遗忘,欢迎您!
So, here what I did, without taggit_template_tags2, probabily can be ottimized, you're welcome!
我的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 %}
又快又简单!
这篇关于从标签数量中排除一些帖子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!