Django AttributeError“”对象没有属性“”

Django AttributeError " " object has no attribute " "

我正在研究 CS50w 网络的 followings/followers 功能。我一直在数粉丝数:

这是我的模型:

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 并尝试获取“关注者”,我使用以下方法成功获取:

{{user.followers.count}}

但是,我不能使用这种方法,因为我需要在后端处理极端情况。


我尝试了另一种方法,但是出现了另一个问题。我试图将 user 传递给 HTMl。但是,如果 user 缺少 followingsfollowers。我无法正确处理这种情况。

这是我的代码以获得更好的想法:

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}} 来获取它们。

如果一开始就没有关注者或追随者怎么办?

local variable 'profile' referenced before assignment

问题是

这里不是用户对象而是跟随模型实例,这就是它起作用的原因。

user = Following.objects.get(user=user_instance)
followings = user.followings.count()

这里写的是user,但是还是Following模型实例

# that is wrong
user = Following.objects.get(user=user_instance)
followers = user.followers.count()

您需要先获取用户实例

user = User.objects.get(...)
followers = user.followers.count()

或者你也可以这样做,但这没有意义,因为你可以从以下实例中获得关注者,但只是为了展示你的方法如何工作:

following_instance = Following.objects.get(user=user_instance)
user = following_instance.user
followers = user.followers.count()