Django 模型在同步数据库后未显示在数据库中

标签 django model syncdb

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

原来的结构是这样的:
/楷模
-- __init__ .py
-- 文件1.py
-- 文件 2.py

__init__ .py 看起来像:

from file1 import File1Model
from file2 import File2Model

我添加了 file3.py
/楷模
-- __init__ .py
-- 文件1.py
-- 文件 2.py
-- file3.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。有什么办法可以弄清楚为什么没有添加新模型?

最佳答案

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

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

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

    class Meta:
        app_label = "my_app"

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

关于Django 模型在同步数据库后未显示在数据库中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10836595/

相关文章:

python - Django默认值表单打开时的日期和时间

python - Django-ManyToMany表提取了错误的信息

neural-network - 使用 Pytorch 保存在 Faster RCNN(COCO 数据集)上训练的最佳模型,避免保存到 "overfitting"

python - 用 pre_save() 填充 django 字段?

python - 如何使 Django QuerySet 批量删除()更高效

django - 如何使用 Django 保存到远程服务器

python - Django 无法更新用户个人资料图片

python - 在 PostgreSQL 数据库上使用 syncdb --migrate 失败。循环依赖

python - Django 没有为模型创建数据库表(无论是 syncdb 还是 South)

python - 从 pyinstaller 制作的外部 exe 文件调用时出现未知命令 "syncdb"