【发布时间】:2021-05-07 15:06:55
【问题描述】:
我正在关注 CS50w 网络的关注者/关注者功能。我一直在数追随者:
这是我的模型:
class Following(models.Model):
"""Tracks the following of a user"""
user = models.ForeignKey(User, on_delete=models.CASCADE)
followings = models.ManyToManyField(User, blank=True, related_name="followers")
使用下面的代码,我可以成功获得以下计数:
user = Following.objects.get(user=user_instance)
followings = user.followings.count()
但是,我无法获得关注者,这是我尝试过的:
user = Following.objects.get(user=user_instance)
followers = user.followers.count()
值得一提的是,如果我通过user并尝试获取`followers',我成功使用:
{{user.followers.count}}
但是,我不能使用这种方法,因为我需要在后端处理极端情况。
我尝试了另一种方法,但是出现了另一个问题。我试图将user 传递给 HTMl。但是,如果user 缺少followings 或followers。我无法正确处理这种情况。
这是我的代码以获得更好的想法:
try:
# Gets the profile
profile = Following.objects.get(user=user_instance)
except Following.DoesNotExist:
followings = 0 # I know these are wrong, but IDK what to do
followers = 0
我可以使用{{profile.followings.count}} & {{profile.followers.count}} 来获取它们。
如果一开始就没有追随者或追随者怎么办?
赋值前引用的局部变量“profile”
【问题讨论】: