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

问题描述 投票:0回答:1

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

{{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”

python django cs50
1个回答
2
投票

问题是

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

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

这里写的是user,但它仍然是Following model实例

# 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()
© www.soinside.com 2019 - 2024. All rights reserved.