Django 中跨 app 创建外键、多对多引用的方法

时间:2023-03-10 06:03:58
Django 中跨 app 创建外键、多对多引用的方法

问题描述

我的 Django 项目中有两个 app。

PersonalCenter app下的 models.py 下定义了一个 Footprint 类:

Django 中跨 app 创建外键、多对多引用的方法

LoginAndRegister app 下的 models.py下的 User 类中,我想建立与 Footpint 的多对多关联:

Django 中跨 app 创建外键、多对多引用的方法

如图所示,在文件头已经 import 了 Footprint 类,但是运行 makemigrations 命令后却出现错误,显示 Footprint 类找不到:

ERRORS:
LoginAndRegister.User.footprints: (fields.E300) Field defines a relation with model 'Footprint', which is either not installed, or is abstract.
LoginAndRegister.User.footprints: (fields.E307) The field LoginAndRegister.User.footprints was declared with a lazy reference to 'LoginAndRegister.footprint', but app 'LoginAndRegister' doesn't provide model 'footprint'.
LoginAndRegister.User_footprints.footprint: (fields.E307) The field LoginAndRegister.User_footprints.footprint was declared with a lazy reference to 'LoginAndRegister.footprint', but app 'LoginAndRegister' doesn't provide model 'footprint'.

解决办法

直接用 app名.类名 这种形式即可成功引用:

Django 中跨 app 创建外键、多对多引用的方法

同理,跨 app 外键的引用也是如此。