【问题标题】:Django AttributeError " " object has no attribute " "Django AttributeError " " 对象没有属性 " "
【发布时间】: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 缺少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}} 来获取它们。

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

赋值前引用的局部变量“profile”

【问题讨论】:

    标签: django cs50


    【解决方案1】:

    问题是

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

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

    你在这里写用户,但它仍然是跟随模型实例

    # 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()
    

    【讨论】:

    • 感谢您的帮助。我设法做对了。但是,我仍然不明白为什么从Following 对象获取关注者不起作用。你能澄清一下吗?
    • 为了从Following中获取它,你需要这样做:following_instance= Following.objects.get(user=user_instance)然后followings = following_instance.followings.count()
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-22
    • 2018-02-11
    • 2015-03-24
    • 2018-01-14
    • 2018-07-31
    • 2021-01-12
    • 2016-12-19
    相关资源
    最近更新 更多