【问题标题】:Django custom user model meta overlaps when importing from another project从另一个项目导入时,Django 自定义用户模型元重叠
【发布时间】:2020-03-18 16:31:13
【问题描述】:

我正在重新制作一个脚本,以使用 python3 将旧 python2 项目中的数据同步到新项目。最后一位程序员使其工作的方式似乎是将新模型和旧模型都导入到旧项目中的脚本中,使用:

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 显示“user”,这可能是扩展 AbstractUser 时的默认 app_label,它可能忽略了我模型中的 app_label 属性并使用了 AbstractUser 中的属性。

关于如何使它工作的任何想法?也对不起我的英语。

编辑 UserProfile 模型:

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

【问题讨论】:

  • 您可以通过在Meta 选项中指定db_table 选项来告诉Django 将哪个表用于模型,如here 所述。
  • 是的,我知道我可以做到,问题是我在 Meta 中指定的任何内容都会在我导入模型时被 AbstractUser 覆盖。它适用于它自己的应用程序,当我将它导入旧应用程序时它会失败。
  • 我不明白您所说的“导入模型”是什么意思。您必须提供有关您正在做的事情的更多详细信息。 sys.path.append... 毫无意义。 django 中的任何模型都需要成为您添加到 INSTALLED_APPS 的应用程序的一部分。
  • 我知道,对吧?但是当他们把代码给我时,它的工作方式是这样的,sys.path 行让 python 从另一个目录导入,在这种情况下是从另一个整个项目。
  • 我知道它可以通过这种方式从您项目之外的另一个文件夹中导入,但您仍然需要定义您的应用程序才能使模型工作。您必须向我们展示您的新项目的更多代码。 INSTALLED_APPS 是什么? UserProfile 型号和User 型号是什么。 app_label 不是来自 AbstractUser,因为它是 'django.contrib.auth' 应用程序的一部分。

标签: python django


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-24
    • 2021-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多