django-taggit - 如何显示与每个记录相关的标签

21

我在一个项目中使用django-taggit,成功地将标签与特定记录保存和绑定。现在的问题是如何显示与每个记录相关的标签?

例如,在我的页面中,我想显示一个包含标题和内容的记录,并在其下方显示与该记录绑定的标签。

在views.py和mytemplate.html文件中应该放置什么?非常感谢提供实际示例。

2个回答

36

models.py

from django.db import models
from taggit.managers import TaggableManager

class MyObject(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()

    tags = TaggableManager()

视图.py

from django.views.generic import simple

def show_object(request):
    """ View all objects """
    return simple.direct_to_template(request,
        template="folder/template.html",
        extra_context={
            'objects':MyObject.objects.all(),
        }) 

模板.html

{% for object in objects %}
    <h2>{{ object.title }}</h2>
    <p>{{ object.content }}</p>
    <ul>
        {% for tag in object.tags.all %}
            <li> {{ tag.name }} </li>
        {% endfor %}
    </ul>
{% endfor %}

这将为您创建的每个对象创建一个额外的数据库查询。如果您有很多对象,那么这可能会使事情变得非常缓慢。我曾经遇到过这种情况,并正在寻找解决方案。 - teewuane
我回复有些晚了@teewuane,但是你说得对。通过使用preselect_related预先获取标签可以减少它的大小。 - Timmy O'Mahony
from django.views.generic import simple 对我不起作用。这个模块已经被弃用了吗? - Arun V Jose

22

如果你很着急,也可以尝试:

{{context_name.tags.all|join:", "}}

1
这正是我所需要的。 - AncientSwordRage

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接