python - 从另一个项目导入时,Django 自定义用户模型元重叠
问题描述
我正在重新制作一个脚本,以将数据从旧的 python2 项目同步到新的 python3 项目。最后一位程序员使它工作的方式似乎是将新模型和旧模型都导入到旧项目中的脚本中,使用:
sys.path.append("route to the new project")
它适用于从新项目中导入除自定义用户模型之外的每个模型,当我尝试使用它时,例如使用 UserProfile.objects.all() 它会崩溃:
relation "user_userprofile" does not exist
第 1 行:从“user_userprofile”中选择“user_userprofile”。“id”
右表是 user_models_userprofile,因为包含模型的应用是“user_models”而不是“user”。
导入模型中的 app_label 显示“用户”,这可能是扩展 AbstractUser 时的默认 app_label,它可能忽略了我模型中的 app_label 属性并使用了 AbstractUser 中的属性。
关于如何使其工作的任何想法?也对不起我的英语。
编辑 用户配置文件模型:
class UserProfile(AbstractUser):
class meta:
app_label = 'user_models'
phone_number = models.IntegerField(default=0)
mail = models.CharField(max_length=50, default='example@example.com')
companies = models.ManyToManyField(Company)
tour_completed = models.BooleanField(default=False)
def __str__(self):
return self.username
没有“用户”模型,它只是那个自定义模型。
我使用导入模型
sys.path.append('route to new project')
from user_models.models import UserProfile
解决方案
最后,我找到了一种方法来更正用户和公司关系中的 app_label 和 db_table。
首先导入模型,然后覆盖 _meta 属性。
from user_models.models import UserProfile
UserProfile._meta.db_table="user_models_userprofile"
UserProfile._meta.app_label="user_models"
UserProfile.companies.through._meta.db_table="user_models_userprofile_companies"
UserProfile.companies.through._meta.app_label="user_models"
不是更漂亮的方法,但它有效。
推荐阅读
- .net - 最新的稳定、不稳定和预发布包之间有什么区别
- c++ - Runtime 如何在运行时推断类型?
- javascript - Spring Framework:接收 POST 请求时如何接受对象数组作为数据参数之一?
- c# - 通过 BitmapMetadata 更改 JPEG 文件的 Windows 元数据会清除未指定的元数据
- c# - 用户控件作为 DataTemplate 没有 DataContext (null)
- circuit-sdk - 有没有办法将 Circuit 集成到类似于 iFrames 的网站中?
- c# - 是否可以从 .NET Core 中间件中检索控制器的操作结果?
- javascript - 反应功能组件中使用和不使用useEffect的区别
- angular9 - ngx-bootstrap typeahead 从 ngrx 商店中选择
- laravel - 如何将从 Botman 收集的数据持久保存到 MySQL