python - Django:在ManyToManyField上连接字符串

标签 python django

我正在尝试制作一个模板过滤器来显示谁喜欢某个帖子。每条评论都包含一个 ManyToManyField ,其中包含对帖子进行投票的用户。我正在尝试使用 join 方法来简化我的代码,而不是使用 for 循环。这不起作用,我收到错误 ManyToManyField is not iterable。

 #post.html
    ...
    <span class="tooltip_text">{{ comment.user_upvotes.all|format_upvote_users }}</span>
    ...

#template_filters.py
@register.filter
def format_upvote_users(queryset):
    # This works:
    upvoters = ''
    for user in queryset:
        upvoters += ', ' + user
    # This doesn't:
    upvoters = ','.join(user in queryset)
    ...
    return upvoters

最佳答案

您需要这样做:

upvoters = ','.join(user for user in queryset)

参见 ( Docs )

关于python - Django:在ManyToManyField上连接字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49566925/

相关文章:

python - 替换 Python 中的深度循环

python - 如何在 PyOpenGL 中使用 gluLookAt?

django 3在表单验证中使用pk重定向

python - Runserver的Unicodedecodeerror

javascript - 批量编辑复杂文本文件

python - 如何使用多个索引从 NumPy 数组中获取值

python - Boost - 无法包装传入变量

Django:Elastic Beanstalk - 无法创建新的 RDS 数据库。 [DBSubnets:选项值无效]

django - ValueError at/Missing staticfiles manifest entry for ''

python - Django:按用户过滤 ModelChoiceField