我试图在创建表后立即添加一些数据到数据库中,使用 post_syncdb 信号。

signals.post_syncdb.connect(init)

然后在init函数中,我想设置权限,所以我使用

ct = ContentType.objects.get(app_label='news', model='Article')
Permission(name='Approve articles', codename='can_approve_article', content_type=ct)

但是如果我删除所有的表并运行 syncdb, ,我得到

...
File "...\base\functions\init.py", line 11, in init
  ct = ContentType.objects.get(app_label='news', model='Article')
...
django.contrib.contenttypes.models.DoesNotExist: ContentType matching query does not exist.

我做过的一些测试:

  • 如果我在外面尝试这段代码,效果很好 syncdb.
  • 如果我让的话它也可以正常工作 syncdb 创建没有此代码的所有表,然后添加此代码并运行syncdb,而无需进行任何更改。
  • 我很确定它曾经有效,但从那时起我在其他地方改变了很多东西,所以我不知道从哪里开始。
  • 我在不同应用程序中的其他模型上遇到相同的错误。
  • 该信号被触发大约 10 次,只有前几次抛出错误。

非常感谢您的任何提示!

有帮助吗?

解决方案

将其添加到 init 函数的开头:

 from django.contrib.contenttypes.management import update_all_contenttypes
 update_all_contenttypes() # make sure all content types exist
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top