在 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/