首页 > 解决方案 > 从另一个项目导入时,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

标签: pythondjango

解决方案


最后,我找到了一种方法来更正用户和公司关系中的 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"

不是更漂亮的方法,但它有效。


推荐阅读