Having problems with a model in one of my django apps.
I can make an instance of the model, but when I go to access it, I get an error:
# create and save model instance
user_form = UserSearchForm(user=user)
user_form.save()
# Then later
first_user_form = UserSearchForm.objects.all()[0]
(1146, "Table 'project.app_tablename' doesn't exist")
Request Method: GET
Request URL: http://10.0.75.1:8000/search/
Django Version: 1.9.5
Exception Type: ProgrammingError
Exception Value:
(1146, "Table 'project.app_tablename' doesn't exist")
Exception Location: /opt/project-venv/lib/python3.4/site-packages/MySQLdb/connections.py in query, line 280
Python Executable: /opt/project-venv/bin/python
Python Version: 3.4.3
Python Path:
['/opt/project/project',
'/opt/project-venv/lib64/python34.zip',
'/opt/project-venv/lib64/python3.4',
'/opt/project-venv/lib64/python3.4/plat-linux',
'/opt/project-venv/lib64/python3.4/lib-dynload',
'/usr/lib64/python3.4',
'/usr/lib/python3.4',
'/opt/project-venv/lib/python3.4/site-packages']
Server time: Tue, 28 Mar 2017 22:50:16 +0000
I'm using Django 1.95 and I tried the following from the linked answer (https://stackoverflow.com/a/36565161/2516846):
- Delete app migrations folder
- Drop all app tables, e.g. DROP TABLE search_usersearchform
- Delete all migrations from db: DELETE FROM django_migrations WHERE app = 'search'.
- python manage.py makemigrations search
- python manage.py migrate
But when I run migrate, it gives error:
django.db.utils.ProgrammingError: relation "search_usersearchform" already exists
Summary: Cannot create model again as relation already exists, yet cannot access model in my app as it says table doesn't exist
Is there a reference to this table/model stored else where which I need to remove? I don't know how the relation can already exist if I dropped the table, deleted migrations folder and removed migrations from db
EDIT
Okay finally got this sorted.
My project had two databases, the 'default' db, using postgres, and the 'secondary' db, using mysql.
When I created a new model in my app, and ran the migration, the table was added to the default db.
This allowed me to create an instance of the new model.
However when I went to access a previously saved instance, I got the error saying the table does not exist.
Turns out it was caused by my apps router.py, which redirected any queries to the 'secondary' db, which of course did not have the table.
To fix this, I added conditionals to the db_for_write and db_for_read methods in router.py, to route those models to the 'default' db.