python - Django:操纵 for 循环以不同方式呈现信息

标签 python django

在 Instagram/Facebook 上的帖子下方,您会看到类似“第 1 个人、第 2 个人和其他 10 个人喜欢此帖子”的文字。我想知道如何使用 Django 来实现网站的相同效果? 通常,我会使用像这样的 for 循环来循环所有喜欢者的姓名;

{% for UserModel in post.likers.all %}
    {{ UserModel.userprofile.first_name }}
{% endfor %}

但是,这并不能让我达到前面提到的预期效果,而且当点赞人数达到数百时,时间肯定会太长。关于如何做到这一点有什么想法吗?谢谢!

最佳答案

您必须自己处理该逻辑,例如在模型方法中(见下文)。

基本上,您希望根据喜欢该帖子的人数返回不同的字符串。对于每种情况,要么不返回任何内容(0 个喜欢),要么返回喜欢它的人的联合列表(1 - 3 个喜欢),要么返回前三个喜欢它的人的联合列表,其余的喜欢计数(> 3 个喜欢)。

from django.db import models


class Post(models.Model)

    # ... your model properties here

    def display_likers(self):

        # how many people liked this?
        num = self.likers.count()

        if num == 0:
            # nobody liked this. return simple string.
            return "Nobody likes this."

        elif num < 4:
            # 1 to 3 people liked this. join their names and
            # return that as a string.
            likers = ', '.join(x.userprofile.first_name for x in self.likers.all())
            return '{} like this'.format(likers)

        else:
            # more than 3 people liked this. return the first 3
            # names and count the remaining likers.
            # note the indexing after all() to only get 3 entries.
            three_likers = ', '.join(
                x.userprofile.first_name for x in self.likers.all()[:3]
            )
            more_count = num - 3
            return '{} and {} others like this'.format(three_likers, more_count)

关于python - Django:操纵 for 循环以不同方式呈现信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46285026/

相关文章:

java - Node : Where or How to write complicated business logic?

python - 为什么在这段代码中查找素数,is_prime(9) 返回 True?

python - 配置 MySQL 以与 Django 一起使用

django - 在 django 1.7+ 中,south.signals.ran_migration 的等价物是什么?

Python 方法访问器在每次访问时创建新对象?

python - 无法使用 BS4 从表格中仅提取可见文本

java - 实现服务器推送

python - 模块未找到错误 : No module named 'pip.download' when trying to install Python package for Django

python - 为 super 用户以外的用户排除 Django 管理中的字段

python - E1101 :Instance of 'Meta' has no 'title' member