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

Django REST API执行migrate报错:'str'对象无'_meta'属性

Django migrate 报错 AttributeError: 'str' object has no attribute '_meta' 解决办法

运行python manage.py migrate时触发如下错误:

AttributeError: 'str' object has no attribute '_meta'

回溯信息指向cacheops的install_cacheops方法,核心问题出在多对多关系的through参数定义上。

问题原因

在Django模型中定义ManyToManyField时,若将through参数设为字符串形式的模型名,而非直接引用模型类对象,cacheops在解析模型元数据时会无法识别该字符串,从而抛出此错误。

修复步骤

  1. 遍历项目中所有包含ManyToManyField的模型,定位使用了through参数的字段
  2. 将字符串形式的中间模型引用替换为直接导入并使用类对象:
    错误写法:
    class Book(models.Model):
        authors = models.ManyToManyField('Author', through='BookAuthor')
    
    正确写法:
    # 先导入对应的模型类
    from .models import Author, BookAuthor
    
    class Book(models.Model):
        authors = models.ManyToManyField(Author, through=BookAuthor)
    
  3. 若中间模型属于其他应用,需跨应用导入:
    from apps.authors.models import Author, BookAuthor
    
    class Book(models.Model):
        authors = models.ManyToManyField(Author, through=BookAuthor)
    

额外排查

  • 确认所有多对多关系的through参数均使用类对象而非字符串
  • 清理项目的.pyc文件,重启开发环境后重新运行python manage.py migrate

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 10:01:09