django несколько баз данных django.db.utils.OperationalError: такой таблицы нет: django_content_type

#django #django-models #django-database

Вопрос:

Я пытаюсь сохранить свои таблицы задач сельдерея в tasks базе данных, которая не имеет ничего общего с другими таблицами, но я продолжаю получать эту ошибку.

sqlite3.OperationalError: такой таблицы нет: django_content_type

Я бы предпочел не иметь дополнительных таблиц, которые я не использую в задачах сельдерея, таких как пользователи или другие мои модели

поэтому я создал две абстрактные модели для своих баз данных:

 class TaskModel(models.Model):  class Meta:  abstract = True  _db = 'tasks'  class CeleryTasks(TaskModel):  ...   class DefaultModel(models.Model):  class Meta:  abstract = True  _db = 'default'  class MyDefaultDatabaseModel(DefaultModel):  ...  

и мой маршрутизатор базы данных выглядит так:

 class DatabaseRouter:  tasks_models = ['CeleryTasks']   def db_for_read(self, model, **hints):  """ reading model based on params """  if not hasattr(model, 'Meta'):  return None  return getattr(model.Meta, '_db', None)   def db_for_write(self, model, **hints):  """ writing model based on params """  if not hasattr(model, 'Meta'):  return None  return getattr(model.Meta, '_db', None)   def allow_relation(self, obj1, obj2, **hints):  if hasattr(obj1._meta, '_db') and hasattr(obj2._meta, '_db'):  return obj1._meta._db == obj2._meta._db  return None   def allow_migrate(self, db, app_label, model_name=None, **hints):  print(  f'allow migration database router invoked with args db={db},app_label={app_label},model_name={model_name},hints={hints}')  if db == 'tasks':  if model_name in self.tasks_models:  print('returning True')  return True  print('returning False')  return False  print('returning None')  return None  

Когда я выполню

python manage.py миграция —база данных=задачи

и мои полные журналы ошибок могут помочь:

 allow migration database router invoked with args db=tasks,app_label=contenttypes,model_name=contenttype,hints={'model': lt;class '__fake__.ContentType'gt;} returning False Traceback (most recent call last):  File "/home/myhome/.local/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute  return self.cursor.execute(sql, params)  File "/home/myhome/.local/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py", line 413, in execute  return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: django_content_type  The above exception was the direct cause of the following exception:  Traceback (most recent call last):  File "manage.py", line 21, in lt;modulegt;  main()  File "manage.py", line 17, in main  execute_from_command_line(sys.argv)  File "/home/myhome/.local/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line  utility.execute()  File "/home/myhome/.local/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute  self.fetch_command(subcommand).run_from_argv(self.argv)  File "/home/myhome/.local/lib/python3.8/site-packages/django/core/management/base.py", line 330, in run_from_argv  self.execute(*args, **cmd_options)  File "/home/myhome/.local/lib/python3.8/site-packages/django/core/management/base.py", line 371, in execute  output = self.handle(*args, **options)  File "/home/myhome/.local/lib/python3.8/site-packages/django/core/management/base.py", line 85, in wrapped  res = handle_func(*args, **kwargs)  File "/home/myhome/.local/lib/python3.8/site-packages/django/core/management/commands/migrate.py", line 267, in handle  emit_post_migrate_signal(  File "/home/myhome/.local/lib/python3.8/site-packages/django/core/management/sql.py", line 48, in emit_post_migrate_signal  models.signals.post_migrate.send(  File "/home/myhome/.local/lib/python3.8/site-packages/django/dispatch/dispatcher.py", line 177, in send  return [  File "/home/myhome/.local/lib/python3.8/site-packages/django/dispatch/dispatcher.py", line 178, in lt;listcompgt;  (receiver, receiver(signal=self, sender=sender, **named))  File "/home/myhome/PycharmProjects/venv/iranPay/lib/python3.8/site-packages/constance/apps.py", line 28, in create_perm  content_type, created = ContentType.objects.using(using).get_or_create(  File "/home/myhome/.local/lib/python3.8/site-packages/django/db/models/query.py", line 573, in get_or_create  return self.get(**kwargs), False  File "/home/myhome/.local/lib/python3.8/site-packages/django/db/models/query.py", line 425, in get  num = len(clone)  File "/home/myhome/.local/lib/python3.8/site-packages/django/db/models/query.py", line 269, in __len__  self._fetch_all()  File "/home/myhome/.local/lib/python3.8/site-packages/django/db/models/query.py", line 1308, in _fetch_all  self._result_cache = list(self._iterable_class(self))  File "/home/myhome/.local/lib/python3.8/site-packages/django/db/models/query.py", line 53, in __iter__  results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)  File "/home/myhome/.local/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1156, in execute_sql  cursor.execute(sql, params)  File "/home/myhome/.local/lib/python3.8/site-packages/django/db/backends/utils.py", line 98, in execute  return super().execute(sql, params)  File "/home/myhome/.local/lib/python3.8/site-packages/django/db/backends/utils.py", line 66, in execute  return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)  File "/home/myhome/.local/lib/python3.8/site-packages/django/db/backends/utils.py", line 75, in _execute_with_wrappers  return executor(sql, params, many, context)  File "/home/myhome/.local/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute  return self.cursor.execute(sql, params)  File "/home/myhome/.local/lib/python3.8/site-packages/django/db/utils.py", line 90, in __exit__  raise dj_exc_value.with_traceback(traceback) from exc_value  File "/home/myhome/.local/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute  return self.cursor.execute(sql, params)  File "/home/myhome/.local/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py", line 413, in execute  return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: no such table: django_content_type ``  

Комментарии:

1. какую команду вы выполняете?

2. @akashpagar я только что обновил свой вопрос

3. можете ли вы подтвердить, какое значение вы получаете для базы данных внутри allow_migrate с помощью pdb?

4. Я напечатал все аргументы, если вы имеете в виду, что @akashpagar

5. таким образом, в этом случае model_name=contenttype отсутствует в списке переменных вашего класса, поэтому он выдает ложное условие.