python - Django 模板 - 打印逗号分隔的 ManyToManyField,将结果列表排序到字典中?

标签 python django django-templates

我有一个用于管理期刊文章列表的 Django 项目。主要模型是Article。这有各种字段来存储文章标题、发布日期、主题以及文章中提到的公司列表等内容。 (company 是它自己的模型)。

我想要一个打印文章列表的模板,按类别排序,并列出提到的公司。

但是,我遇到了两个问题。

首先,company 字段是一个 ManyToMany 字段。我现在成功地打印了这个,使用 all 可迭代,多亏了这个 SO 问题 =)。 (不过很好奇,这个 all 可迭代记录在 Django 文档中的什么地方?)

listing objects from ManyToManyField

但是,我想在每一项之后打印“,”(逗号后跟空格),除了最后一项。所以输出将是:

Joe Bob Company, Sarah Jane Company, Tool Company

而不是:

Joe Bob Company, Sarah Jane Company, Tool Company,

如何使用 Django 的模板系统实现这一点?

其次,每个 Article 都有一个名为 category 的 CharField,用于存储文章的类别。如果可能的话,我希望文章按类别分类。所以我使用 QuerySet,并在 article_list 中获得了一个很好的相关文章列表。然后,我使用 regroup 模板标签将其分类并打印每个类别。

{ 'tennis': ('article_4', 'article_5')
  'cricket': ('article_2', 'article_3')
  'ping pong': ('article_1')
}

但是,在将输入列表传递给 regroup 之前,我需要确保它已排序。我的问题是,是使用 dictsort 模板标签在模板内对其进行排序更好,还是应该改用 QuerySet 的 order_by 调用?

而且我认为最好使用 regroup,而不是尝试在 View 中用 Python 自己编写代码?

干杯, 维克多

最佳答案

第一个问题

像使用python一样加入过滤器

{{ article.company.all|join:", " }}

http://docs.djangoproject.com/en/dev/ref/templates/builtins/#join

第二个问题

My question is, is it better to use the dictsort template-tag to sort this inside the template, or should I use QuerySet's order_by call instead?

我会使用 QuerySet 的 order_by。我喜欢在数据库中做这样的事情。因为对于庞大的数据集,您可以使用数据库索引。

And I assume it's better to use regroup, rather than trying to code this myself in Python inside the view?

重组。使用 python 原生函数肯定更好。

关于python - Django 模板 - 打印逗号分隔的 ManyToManyField,将结果列表排序到字典中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3177461/

相关文章:

c++ - 我怎样才能在cython中调用这个函数?

python - 在 Python 中从 matplotlib 中的散点图绘制曲线?

python - 从 Django 调用 Postgres SQL 存储过程

python - 在 html 页面中填写注册表单后,出现此错误并使用用户名和密码并将值存储在登录表单中

python - Django 模板 : overriding blocks of included children templates through an extended template

python - throw [HTTPError : HTTP Error 503: Service Unavailable] Error after the selenium tests are done using Python

python - 使用 else pass 的列表理解

python - 获取 django 模型字符串字段作为 str 而不是 unicode

python - Django Templatetag,列表索引超出范围

Django 在模板中使用链接参数的值