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

Django实现收藏功能时出现Profile无favourite属性AttributeError如何解决

问题解决方案

核心原因是字段拼写不匹配:报错信息中指向的属性是英式拼写的favourite,但你在Profile模型中定义的多对多字段为美式拼写的favorite,二者存在1个字母的差异,Django无法在模型实例上找到对应属性,因此抛出AttributeError。

修复方案按优先级排序:

  • 检查所有调用Profile对象收藏属性的代码(视图、模板、序列化器等位置),将所有favourite的调用改为和模型定义一致的favorite即可。
    示例修正代码:
# 错误调用
request.user.profile.favourite.add(accommodation_instance)

# 修正后调用
request.user.profile.favorite.add(accommodation_instance)
  • 如果你需要统一使用英式拼写,可反向修改模型字段定义:
class Profile(models.Model):
    user = models.OneToOneField(User, related_name='profile', on_delete=models.CASCADE)
    # 其余字段省略
    favourite = models.ManyToManyField(Accomodation, related_name='favorited_profiles')

修改后执行迁移命令同步数据库:

python manage.py makemigrations
python manage.py migrate
  • 若拼写统一后仍报错,检查是否是开发服务器缓存未清空、旧迁移文件未生效导致,重启服务并重新执行迁移命令即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 21:54:07