gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 14:03:56 25 4
gpt4 key购买 nike

我有一个模型文件夹,其中在数据库中已有的文件中有几个模型。我刚刚添加了另一个文件/模型,但是当我运行 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com