Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/jpa/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Django post_syncdb上不存在ContentType匹配查询_Django_Signals_Syncdb_Contenttype - Fatal编程技术网

Django post_syncdb上不存在ContentType匹配查询

Django post_syncdb上不存在ContentType匹配查询,django,signals,syncdb,contenttype,Django,Signals,Syncdb,Contenttype,我试图在创建表后立即使用post\u 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) 但是如

我试图在创建表后立即使用
post\u 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

现在的“解决方案”是捕获DoesNotExist异常并传递。在随后的一次信号触发过程中,可以确定contenttype,并且一切正常。它可以工作,但如果有人有一个更漂亮的解决方案,我仍然很好奇。这在Django 1.10中不再有效-不确定何时删除update_all_contenttypes或替换命令是什么。