【问题标题】:Django Models not Showing Up in DB after syncdbsyncdb 后 Django 模型未显示在数据库中
【发布时间】:2012-06-05 21:17:22
【问题描述】:

我有一个模型文件夹,其中包含数据库中已经存在的文件中的一些模型。我刚刚添加了另一个文件/模型,但是当我运行 syncdb 时它没有被添加到数据库中。我试过 manage.py validate 并且运行良好。我也运行了代码,只有当它尝试使用“表不存在”保存时才会失败。

原来的结构是这样的:
/型号
-- __init__.py
-- file1.py
-- 文件2.py

__init__.py 看起来像:

from file1 import File1Model
from file2 import File2Model

我添加了 file3.py
/型号
-- __init__.py
-- file1.py
-- 文件2.py
-- 文件3.py

并修改了__init__.py

from file1 import File1Model
from file2 import File2Model
from file3 import File3Model

还有 file3 的内容(名称可能已更改以保护无辜者,但除此之外它是确切的文件):
更新:刚刚尝试添加主键,因为 id 字段可能与自动添加的整数主键 id 混淆。还尝试了一些变化,但没有骰子。

from django.db import models
from django.contrib.auth.models import User


class File3Model(models.Model):
    user = models.OneToOneField(User)
    token = models.CharField(max_length=255, blank=False, null=False)
    id = models.CharField(primary_key=True, max_length=255)

    class Admin:
        pass

    class Meta:
        app_label = 'coolabel'

    def __unicode__(self):
        return self.user.username

    @staticmethod
    def getinstance(user, token, id):
        try:
            instance = File3Model.objects.get(pk=id)
            if instance.token != token:
                instance.token = token
                instance.save()
            return instance
        except:
            pass
        instance = File3Model()
        instance.user = user
        instance.token = token
        instance.id = id
        instance.save()
        return instance

所以在本例中,File1Model 和 File2Model 已经在 DB 中,并且在 syncdb 之后仍保留在 DB 中。但是,即使重新运行 syncdb,也不会添加 File3Model。有什么方法可以弄清楚为什么没有添加新模型??

【问题讨论】:

  • 刚试了还是不行。

标签: django model syncdb


【解决方案1】:

如果您在models.py 之外定义模型,则必须在模型Meta 类上设置app_label 属性。

编辑:app_label 必须引用您的 INSTALLED_APPS 设置中的应用程序。它可能应该与模型目录所在的应用程序的名称相匹配,除非您有充分的理由不这样做。这似乎是你的问题。

class File3Model(models.Model):
    foo = models.CharField(...)
    ...

    class Meta:
        app_label = "my_app"

请注意,syncdb 永远不会从数据库中删除任何表。其他表可能是在将 models.py 替换为目录结构之前使用 syncdb 创建的。

【讨论】:

  • 在 Meta 类中设置了 app_label 字段,但仍未添加到数据库中。
  • app_label 必须是您的INSTALLED_APPS 设置中的应用程序。我已将此添加到答案中。
【解决方案2】:

为我的应用设置 app_label 可以解决我的问题。

【讨论】:

    【解决方案3】:

    你为什么要拆分模型并拥有模型文件夹,而不是将模型放在 models.py 中?

    在我自己的项目中,models.py 中有大约 10 个模型,我很好。

    你也可以试试manage.py syncdb --all

    我认为最好将所有模型保存在一个文件中并像from my_app.models import model_name 一样导入它们,而不是记住将必要的模型导入models/__init__.py。顺便说一句,您避免了许多问题和冗长的导入,并且不关心 some_modelmodels/*.py 文件中的位置。

    谢谢,

    苏丹

    【讨论】:

    • 感谢您的建议。但是,我正在使用现有代码,并认为将所有内容移回 models.py 文件会很愚蠢。我更愿意将所有内容都保留在模型目录中。
    【解决方案4】:

    轰隆隆!

    我为新模型使用了不同的 app_label,但它在整个模型组中必须相同。

    其他型号的标签是“mediocrelabel”,而我的新型号的标签是“coolabel”。我将新模型的标签更改为“mediocrelabel”,现在它们已正确添加到数据库中。

    感谢您的帮助,伙计们!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-17
      • 1970-01-01
      • 1970-01-01
      • 2020-03-03
      • 1970-01-01
      • 2011-11-19
      • 2013-02-11
      • 2017-12-26
      相关资源
      最近更新 更多