You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django中Profile模型following_usr序列化报错的解决咨询

问题解决:Profile序列化中following_usr字段错误

错误原因

你遇到的AttributeError是因为self.user.following.all()返回的是Profile对象的QuerySet,而非User对象。这是因为你在Profile模型的follower字段上设置了related_name="following",反向关联指向的是Profile实例(表示哪些Profile的follower包含当前User),所以遍历每个元素时,它是Profile对象,没有username属性。

同时,你的模型字段语义存在混淆:follower字段当前表示的是「关注该Profile用户的人」,而self.user.following对应的是「所有将当前用户设为关注者的Profile」,这和你想要的「当前用户关注的人」逻辑完全相反。

两种解决方式

方式1:修正序列化逻辑(不修改模型)

直接遍历self.user.following返回的Profile对象,取出关联的User的username:

def serialize(self):
    return {
        "user_id": self.user.id,
        "user": self.user.username,
        "followers": self.follower.count(),
        "followers_usr": [user.username for user in self.follower.all()],
        "following": self.user.following.count(),
        # 修正此处,从Profile对象中取关联User的username
        "following_usr": [profile.user.username for profile in self.user.following.all()]
    }

方式2:重构模型关联(更推荐,语义清晰)

调整模型字段名和关联逻辑,让语义更符合业务场景:

class Profile(models.Model):
    id = models.AutoField(primary_key=True)
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="user_profile")
    # 字段改为following,表示当前用户关注的人
    following = models.ManyToManyField(User, blank=True, related_name="followers")
    
    def __str__(self):
        return f"{self.user.username}"
    
    def serialize(self):
        return {
            "user_id": self.user.id,
            "user": self.user.username,
            # followers:关注当前用户的人(粉丝),通过User的反向关联获取
            "followers": self.user.followers.count(),
            "followers_usr": [user.username for user in self.user.followers.all()],
            # following:当前用户关注的人,直接取Profile的following字段
            "following": self.following.count(),
            "following_usr": [user.username for user in self.following.all()]
        }

这样修改后,模型的关联逻辑更直观,后续维护也更简单。

内容的提问来源于stack exchange,提问作者GingerBuns

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 10:05:14