必须为'app_label.ModelName'形式。“%model ValueError:无效的模型引用


问题内容

当我python3 manage.py makemigrations,我得到以下错误:

...

  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/db/models/fields/related.py", line 348, in contribute_to_class
    lazy_related_operation(resolve_related_class, cls, self.remote_field.model, field=self)
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/db/models/fields/related.py", line 85, in lazy_related_operation
    return apps.lazy_model_operation(partial(function, **kwargs), *model_keys)
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/db/models/fields/related.py", line 83, in <genexpr>
    model_keys = (make_model_tuple(m) for m in models)
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/db/models/utils.py", line 23, in make_model_tuple
    "must be of the form 'app_label.ModelName'." % model
ValueError: Invalid model reference 'x.qiyun_admin_productconfig_cloudserver.HostType

但是,我的HostType模型路径是这样的:
x.qiyun_admin_productconfig_cloudserver.models.HostType

追溯少了.models。我不知道为什么

请注意,序列化程序和视图(序列化程序视图)在api目录下。

和设置:

...
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
PARENT_DIR = os.path.abspath(os.path.join(BASE_DIR, os.pardir))


sys.path.insert(0, BASE_DIR)
sys.path.insert(0, os.path.join(PARENT_DIR,'x'))
sys.path.insert(0, os.path.join(PARENT_DIR,'x'))
sys.path.insert(0, os.path.join(PARENT_DIR,'x'))
...

INSTALLED_APPS = [
    'django.contrib.admin',
     ....
    'x.qiyun_admin_useradminmanage',  #  
    'x.qiyun_admin_usergroups',  #

    'x.qiyun_admin_productconfig_common', #  
    'x.qiyun_admin_productconfig_cloudserver',  #

    'x.qiyun_admin_financialmanage_ordermanage', # 
    'x.qiyun_admin_financialmanage_financialmanage',

编辑

我在同一models.py(x.qiyun_admin_productconfig_cloudserver.)中有两个Models(AvailableArea,AddressRegion
):

class AvailableArea(models.Model):
    name = models.CharField(max_length=8)
    addressregion = models.ForeignKey(AddressRegion, default=1, related_name='availableareas', on_delete=models.CASCADE)

    def __str__(self):
        return self.name
    def __unicode__(self):
        return self.name

class AddressRegion(models.Model):
    name = models.CharField(max_length=8)

    def __str__(self):
        return self.name
    def __unicode__(self):
        return self.name

您知道,我还应该指定addressregion = models.ForeignKey('qiyun_admin_productconfig_cloudserver.AddressRegion',...)吗?

如果其他模型引用了ForeignKey AddressRegion,我也将其导入。



问题答案:

具有相同错误消息的情况略有不同:

ValueError:无效的模型引用’users.models.MyUser’。字符串模型引用的格式必须为“ app_label.ModelName”。

错误是我modelsMyUser模型的路径中指定的:

AUTH_USER_MODEL = 'users.models.MyUser'

但是我们没有这样做,我们只需要指定包和型号名称

AUTH_USER_MODEL = 'users.MyUser'

错误消失了。