# Table (relation) cannot be found on Postgres

**URL:** <https://forum.djangoproject.com/t/table-relation-cannot-be-found-on-postgres/40006>\
**Category:** Mystery Errors\
**Created:** [March 29, 2025, 10:19am UTC](https://forum.djangoproject.com/t/table-relation-cannot-be-found-on-postgres/40006 "2025-03-29T10:19:13Z")\
**Posts on this page:** 11\
**Page:** 1

<div class="post-metadata">

**Author:** ![alexandremjacques](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/alexandremjacques/32/893_2.png) [@alexandremjacques](https://forum.djangoproject.com/u/alexandremjacques)\
**Post date:** [March 29, 2025, 10:19am UTC](https://forum.djangoproject.com/t/table-relation-cannot-be-found-on-postgres/40006/1 "2025-03-29T10:19:13Z")

</div>

Hi.

I have a legacy Postgres database that I don’t have any control over. I’m trying to create a Django app that, in a separate database connection, also connects to the legacy one. To do that, I created a Database Router that has a `default` connection (for Django models and control tables) and a `legacy` that points to the database in question:

```auto
DATABASES = {
    'default': env.db('DEFAULT_DATABASE_URL'),
    'legacy': env.db('LEGACY_DATABASE_URL'),
}

DATABASE_ROUTERS = ["apps.core.routers.DefaultRouter", "apps.core.routers.LegacyRouter"]

```

- I can see that the connections are ok (I see no errors on server start and if, I change the URLs to something invalid, I do see connection errors);
- Using the Django Toolbar I can check the generated query and that the connection being used by the engine is, in fact, the `legacy` one:

 ![image](https://us1.discourse-cdn.com/flex026/uploads/djangoproject/original/3X/4/a/4a82fff1bc3fbb4df8e1cb30c845946e5a6bccec.png)

- If I copy that query and run it against the database it works but if I try to load a model (`PaintColor`) that maps to the same database table, I receive a `relation "PaintColor" does not exist` error.

One thing to notice is that the legacy database has a `quoteReturningIdentifiers` set to `true` and that affects how I write queries in any database client: I have to quote almost every identifier (table and column names). But, as I mentioned, if I take the Django generated query from DT, I see no issues.

Any help is appreciated.

TIA

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [March 29, 2025, 11:50am UTC](https://forum.djangoproject.com/t/table-relation-cannot-be-found-on-postgres/40006/2 "2025-03-29T11:50:25Z")

</div>

> [@alexandremjacques](#):
>
> but if I try to load a model (`PaintColor`) that maps to the same database table, I receive a `relation "PaintColor" does not exist` error.

It’s difficult-to-impossible to diagnose errors from a description.

Please post the actual code being used here that is throwing the error.

---

<div class="post-metadata">

**Author:** ![alexandremjacques](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/alexandremjacques/32/893_2.png) [@alexandremjacques](https://forum.djangoproject.com/u/alexandremjacques)\
**Post date:** [March 29, 2025, 1:39pm UTC](https://forum.djangoproject.com/t/table-relation-cannot-be-found-on-postgres/40006/3 "2025-03-29T13:39:49Z")

</div>

Sure!

Since it’s a new project where I was trying to prove this concept of 2 different DBs, I have a simple structure:

1. Just one app called `apps.acotone`
2. Two routers
3. One simple view, one model (PaintColor)

`settings.py`

```python
DATABASES = {
    'default': env.db('DEFAULT_DATABASE_URL'),
    'legacy': env.db('LEGACY_DATABASE_URL'),
}

DATABASE_ROUTERS = ["apps.acotone.routers.DefaultRouter", "apps.acotone.routers.LegacyRouter"]

```

`routers.py`

```python
class DefaultRouter:
    route_app_labels = {"auth", "contenttypes"}

    def db_for_read(self, model, **hints):
        if model._meta.app_label in self.route_app_labels:
            return "default"
        return None

    def db_for_write(self, model, **hints):
        if model._meta.app_label in self.route_app_labels:
            return "default"
        return None

    def allow_relation(self, obj1, obj2, **hints):
        if (
                obj1._meta.app_label in self.route_app_labels
                or obj2._meta.app_label in self.route_app_labels
        ):
            return True
        return None

    def allow_migrate(self, db, app_label, model_name=None, **hints):
        if app_label in self.route_app_labels:
            return db == "default"
        return None

class LegacyRouter:
    route_app_labels = {"acotone"}

    def db_for_read(self, model, **hints):
        if model._meta.app_label in self.route_app_labels:
            return "legacy"
        return None

    def db_for_write(self, model, **hints):
        if model._meta.app_label in self.route_app_labels:
            return "legacy"
        return None

    def allow_relation(self, obj1, obj2, **hints):
        if (
                obj1._meta.app_label in self.route_app_labels
                or obj2._meta.app_label in self.route_app_labels
        ):
            return True
        return None

    def allow_migrate(self, db, app_label, model_name=None, **hints):
        if app_label in self.route_app_labels:
            return db == "legacy"
        return None

```

`views.py`

```python
from django.shortcuts import render
from django.views import View

from apps.acotone.models import PaintColor

class PaintColorsHome(View):
    def get(self, request):
        paint_colors = PaintColor.objects.all()

        context = {
            'paint_colors': paint_colors,
        }

        return render(request, 'acotone_home.html', context)

```

`models.py`

```python
from django.db import models

class PaintColor(models.Model):
    color_name = models.CharField(max_length=255, db_column='colorName', primary_key=True)
    color_notation = models.CharField(max_length=255, db_column='colorNotation')
    color_type = models.CharField(max_length=255, db_column='colorType')
    red_value = models.IntegerField(db_column='redValue')
    green_value = models.IntegerField(db_column='greenValue')
    blue_value = models.IntegerField(db_column='blueValue')
    color_family = models.CharField(max_length=255, db_column='colorFamily')
    color_order = models.IntegerField(db_column='colorOrder')
    status = models.CharField(max_length=255, db_column='status')

    class Meta:
        db_table = "PaintColor"
        managed = False

```

The database (sorry, I can’t disclosure much more):

 ![image](https://us1.discourse-cdn.com/flex026/uploads/djangoproject/original/3X/5/e/5e21df5ae7d06559eeb1bed59504eb0a8bc3fff5.png)

The error message:

 ![image](https://us1.discourse-cdn.com/flex026/uploads/djangoproject/original/3X/6/3/634ac1b830521828cf81b991341b1c0f4c94e9bd.png)

Thanks again

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [March 29, 2025, 2:20pm UTC](https://forum.djangoproject.com/t/table-relation-cannot-be-found-on-postgres/40006/4 "2025-03-29T14:20:20Z")

</div>

We need to see the complete error message with the traceback from the server console, not the summary provided on the error page.

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [March 29, 2025, 2:23pm UTC](https://forum.djangoproject.com/t/table-relation-cannot-be-found-on-postgres/40006/5 "2025-03-29T14:23:09Z")

</div>

> [@alexandremjacques](#):
>
> ```auto
> route_app_labels = {"acotone"}
> 
> ```

Are you sure that this is the app label being passed to the router?

I would suggest adding a print statement in your `db_for_read` method to see what’s being supplied.

---

<div class="post-metadata">

**Author:** ![alexandremjacques](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/alexandremjacques/32/893_2.png) [@alexandremjacques](https://forum.djangoproject.com/u/alexandremjacques)\
**Post date:** [March 29, 2025, 4:45pm UTC](https://forum.djangoproject.com/t/table-relation-cannot-be-found-on-postgres/40006/6 "2025-03-29T16:45:41Z")

</div>

Yeah. I’m sure. I did print that to make sure. I’m including the traceback with some debugging statements for `db_for_read()`.

From DT I can see that it tries 21 times before failing (hence the repeated logging - I removed some since it’d be redundant).

```shell
...
[DEBUG] [7ddf800f97314c0ba60ebb5f9ba4d4b4] 2025-03-29 17:26:46,025 - apps.acotone.routers:db_for_read:40 - LegacyRouter model._meta.app_label: acotone
[DEBUG] [7ddf800f97314c0ba60ebb5f9ba4d4b4] 2025-03-29 17:26:46,031 - apps.acotone.routers:db_for_read:37 - LegacyRouter.db_for_read model: <class 'apps.acotone.models.PaintColor'>
[DEBUG] [7ddf800f97314c0ba60ebb5f9ba4d4b4] 2025-03-29 17:26:46,031 - apps.acotone.routers:db_for_read:40 - LegacyRouter model._meta.app_label: acotone
[DEBUG] [7ddf800f97314c0ba60ebb5f9ba4d4b4] 2025-03-29 17:26:46,039 - apps.acotone.routers:db_for_read:37 - LegacyRouter.db_for_read model: <class 'apps.acotone.models.PaintColor'>
[DEBUG] [7ddf800f97314c0ba60ebb5f9ba4d4b4] 2025-03-29 17:26:46,039 - apps.acotone.routers:db_for_read:40 - LegacyRouter model._meta.app_label: acotone
[DEBUG] [7ddf800f97314c0ba60ebb5f9ba4d4b4] 2025-03-29 17:26:46,046 - apps.acotone.routers:db_for_read:37 - LegacyRouter.db_for_read model: <class 'apps.acotone.models.PaintColor'>
[DEBUG] [7ddf800f97314c0ba60ebb5f9ba4d4b4] 2025-03-29 17:26:46,046 - apps.acotone.routers:db_for_read:40 - LegacyRouter model._meta.app_label: acotone
[ERROR] [7ddf800f97314c0ba60ebb5f9ba4d4b4] 2025-03-29 17:26:46,069 - django.request:log_response:248 - Internal Server Error: /acotone/
Traceback (most recent call last):
  File "/Users/alexandremjacques/Development/Projects/Python/tintometrico_admin/.venv/lib/python3.13/site-packages/django/db/backends/utils.py", line 105, in _execute
    return self.cursor.execute(sql, params)
           ~~~~~~~~~~~~~~~~~~~ ^^^^^^^^^^^^^
  File "/Users/alexandremjacques/Development/Projects/Python/tintometrico_admin/.venv/lib/python3.13/site-packages/psycopg/cursor.py", line 97, in execute
    raise ex.with_traceback(None)
psycopg.errors.UndefinedTable: relation "PaintColor" does not exist
LINE 1: ...ntColor"."colorOrder", "PaintColor"."status" FROM "PaintColo...
                                                             ^

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/Users/alexandremjacques/Development/Projects/Python/tintometrico_admin/.venv/lib/python3.13/site-packages/django/core/handlers/exception.py", line 55, in inner
    response = get_response(request)
  File "/Users/alexandremjacques/Development/Projects/Python/tintometrico_admin/.venv/lib/python3.13/site-packages/django/core/handlers/base.py", line 197, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Users/alexandremjacques/Development/Projects/Python/tintometrico_admin/.venv/lib/python3.13/site-packages/django/views/generic/base.py", line 104, in view
    return self.dispatch(request, *args, **kwargs)
           ~~~~~~~~~~~~~ ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/alexandremjacques/Development/Projects/Python/tintometrico_admin/.venv/lib/python3.13/site-packages/django/views/generic/base.py", line 143, in dispatch
    return handler(request, *args, **kwargs)
  File "/Users/alexandremjacques/Development/Projects/Python/tintometrico_admin/apps/acotone/views.py", line 15, in get
    return render(request, 'acotone_home.html', context)
  File "/Users/alexandremjacques/Development/Projects/Python/tintometrico_admin/.venv/lib/python3.13/site-packages/django/shortcuts.py", line 25, in render
    content = loader.render_to_string(template_name, context, request, using=using)
  File "/Users/alexandremjacques/Development/Projects/Python/tintometrico_admin/.venv/lib/python3.13/site-packages/django/template/loader.py", line 62, in render_to_string
    return template.render(context, request)
           ~~~~~~~~~~~~~~~ ^^^^^^^^^^^^^^^^^^
  File "/Users/alexandremjacques/Development/Projects/Python/tintometrico_admin/.venv/lib/python3.13/site-packages/django/template/backends/django.py", line 107, in render
    return self.template.render(context)
           ~~~~~~~~~~~~~~~~~~~~ ^^^^^^^^^
  File "/Users/alexandremjacques/Development/Projects/Python/tintometrico_admin/.venv/lib/python3.13/site-packages/django/template/base.py", line 171, in render
    return self._render(context)
           ~~~~~~~~~~~~ ^^^^^^^^^
  File "/Users/alexandremjacques/Development/Projects/Python/tintometrico_admin/.venv/lib/python3.13/site-packages/django/test/utils.py", line 114, in instrumented_test_render
    return self.nodelist.render(context)
           ~~~~~~~~~~~~~~~~~~~~ ^^^^^^^^^
  File "/Users/alexandremjacques/Development/Projects/Python/tintometrico_admin/.venv/lib/python3.13/site-packages/django/template/base.py", line 1008, in render
    return SafeString("".join([node.render_annotated(context) for node in self]))
                               ~~~~~~~~~~~~~~~~~~~~~ ^^^^^^^^^
  File "/Users/alexandremjacques/Development/Projects/Python/tintometrico_admin/.venv/lib/python3.13/site-packages/django/template/base.py", line 969, in render_annotated
    return self.render(context)
           ~~~~~~~~~~~ ^^^^^^^^^
  File "/Users/alexandremjacques/Development/Projects/Python/tintometrico_admin/.venv/lib/python3.13/site-packages/django/template/loader_tags.py", line 159, in render
    return compiled_parent._render(context)
           ~~~~~~~~~~~~~~~~~~~~~~~ ^^^^^^^^^
  File "/Users/alexandremjacques/Development/Projects/Python/tintometrico_admin/.venv/lib/python3.13/site-packages/django/test/utils.py", line 114, in instrumented_test_render
    return self.nodelist.render(context)
           ~~~~~~~~~~~~~~~~~~~~ ^^^^^^^^^
  File "/Users/alexandremjacques/Development/Projects/Python/tintometrico_admin/.venv/lib/python3.13/site-packages/django/template/base.py", line 1008, in render
    return SafeString("".join([node.render_annotated(context) for node in self]))
                               ~~~~~~~~~~~~~~~~~~~~~ ^^^^^^^^^
  File "/Users/alexandremjacques/Development/Projects/Python/tintometrico_admin/.venv/lib/python3.13/site-packages/django/template/base.py", line 969, in render_annotated
    return self.render(context)
           ~~~~~~~~~~~ ^^^^^^^^^
  File "/Users/alexandremjacques/Development/Projects/Python/tintometrico_admin/.venv/lib/python3.13/site-packages/django/template/loader_tags.py", line 65, in render
    result = block.nodelist.render(context)
  File "/Users/alexandremjacques/Development/Projects/Python/tintometrico_admin/.venv/lib/python3.13/site-packages/django/template/base.py", line 1008, in render
    return SafeString("".join([node.render_annotated(context) for node in self]))
                               ~~~~~~~~~~~~~~~~~~~~~ ^^^^^^^^^
  File "/Users/alexandremjacques/Development/Projects/Python/tintometrico_admin/.venv/lib/python3.13/site-packages/django/template/base.py", line 969, in render_annotated
    return self.render(context)
           ~~~~~~~~~~~ ^^^^^^^^^
  File "/Users/alexandremjacques/Development/Projects/Python/tintometrico_admin/.venv/lib/python3.13/site-packages/django/template/defaulttags.py", line 199, in render
    len_values = len(values)
  File "/Users/alexandremjacques/Development/Projects/Python/tintometrico_admin/.venv/lib/python3.13/site-packages/django/db/models/query.py", line 382, in __len__
    self._fetch_all()
    ~~~~~~~~~~~~~~~ ^^
  File "/Users/alexandremjacques/Development/Projects/Python/tintometrico_admin/.venv/lib/python3.13/site-packages/django/db/models/query.py", line 1928, in _fetch_all
    self._result_cache = list(self._iterable_class(self))
                         ~~~~ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/alexandremjacques/Development/Projects/Python/tintometrico_admin/.venv/lib/python3.13/site-packages/django/db/models/query.py", line 91, in __iter__
    results = compiler.execute_sql(
        chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size
    )
  File "/Users/alexandremjacques/Development/Projects/Python/tintometrico_admin/.venv/lib/python3.13/site-packages/django/db/models/sql/compiler.py", line 1574, in execute_sql
    cursor.execute(sql, params)
    ~~~~~~~~~~~~~~ ^^^^^^^^^^^^^
  File "/Users/alexandremjacques/Development/Projects/Python/tintometrico_admin/.venv/lib/python3.13/site-packages/debug_toolbar/panels/sql/tracking.py", line 235, in execute
    return self._record(super().execute, sql, params)
           ~~~~~~~~~~~~ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/alexandremjacques/Development/Projects/Python/tintometrico_admin/.venv/lib/python3.13/site-packages/debug_toolbar/panels/sql/tracking.py", line 160, in _record
    return method(sql, params)
  File "/Users/alexandremjacques/Development/Projects/Python/tintometrico_admin/.venv/lib/python3.13/site-packages/django/db/backends/utils.py", line 122, in execute
    return super().execute(sql, params)
           ~~~~~~~~~~~~~~~ ^^^^^^^^^^^^^
  File "/Users/alexandremjacques/Development/Projects/Python/tintometrico_admin/.venv/lib/python3.13/site-packages/django/db/backends/utils.py", line 79, in execute
    return self._execute_with_wrappers(
           ~~~~~~~~~~~~~~~~~~~~~~~~~~~ ^
        sql, params, many=False, executor=self._execute
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    )
    ^
  File "/Users/alexandremjacques/Development/Projects/Python/tintometrico_admin/.venv/lib/python3.13/site-packages/django/db/backends/utils.py", line 92, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "/Users/alexandremjacques/Development/Projects/Python/tintometrico_admin/.venv/lib/python3.13/site-packages/django/db/backends/utils.py", line 100, in _execute
    with self.db.wrap_database_errors:
         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/alexandremjacques/Development/Projects/Python/tintometrico_admin/.venv/lib/python3.13/site-packages/django/db/utils.py", line 91, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "/Users/alexandremjacques/Development/Projects/Python/tintometrico_admin/.venv/lib/python3.13/site-packages/django/db/backends/utils.py", line 105, in _execute
    return self.cursor.execute(sql, params)
           ~~~~~~~~~~~~~~~~~~~ ^^^^^^^^^^^^^
  File "/Users/alexandremjacques/Development/Projects/Python/tintometrico_admin/.venv/lib/python3.13/site-packages/psycopg/cursor.py", line 97, in execute
    raise ex.with_traceback(None)
django.db.utils.ProgrammingError: relation "PaintColor" does not exist
LINE 1: ...ntColor"."colorOrder", "PaintColor"."status" FROM "PaintColo...
                                                             ^
[ERROR] [7ddf800f97314c0ba60ebb5f9ba4d4b4] 2025-03-29 17:26:46,110 - django.server:log_message:213 - "GET /acotone/ HTTP/1.1" 500 249489

```

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [March 29, 2025, 7:13pm UTC](https://forum.djangoproject.com/t/table-relation-cannot-be-found-on-postgres/40006/7 "2025-03-29T19:13:03Z")

</div>

When you test this manually, are you using the same credentials as what your Django code is using?

What happens if you use the `manage.py dbshell` command to open up the database connection? Does that work?

What if you open the regular Django shell and try to run the query? (`PaintColor.objects.all()`)

If that doesn’t work, what happens then if you then run that query with the `using` clause?

---

<div class="post-metadata">

**Author:** ![alexandremjacques](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/alexandremjacques/32/893_2.png) [@alexandremjacques](https://forum.djangoproject.com/u/alexandremjacques)\
**Post date:** [March 29, 2025, 8:20pm UTC](https://forum.djangoproject.com/t/table-relation-cannot-be-found-on-postgres/40006/8 "2025-03-29T20:20:29Z")

</div>

> When you test this manually, are you using the same credentials as what your Django code is using?

Yes. I have just 1 set of credentials to access the legacy DB.

> What happens if you use the `manage.py dbshell` command to open up the database connection? Does that work?

It does. If I `\d`I can see Django tables:

```auto
(.venv) .venv ❯ ./manage.py dbshell
psql (17.4, server 16.4 (Debian 16.4-1.pgdg120+1))
SSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384, compression: off, ALPN: none)
Type "help" for help.

tintometricoadmin=> \d
                            List of relations
 Schema | Name | Type | Owner         
--------+-------------------------------+----------+----------------------
 public | auth_group | table | tintometricoadminusr
 public | auth_group_id_seq | sequence | tintometricoadminusr
 public | auth_group_permissions | table | tintometricoadminusr
 public | auth_group_permissions_id_seq | sequence | tintometricoadminusr
 public | auth_permission | table | tintometricoadminusr
 public | auth_permission_id_seq | sequence | tintometricoadminusr
 public | django_admin_log | table | tintometricoadminusr
 public | django_admin_log_id_seq | sequence | tintometricoadminusr
 public | django_content_type | table | tintometricoadminusr
 public | django_content_type_id_seq | sequence | tintometricoadminusr
 public | django_migrations | table | tintometricoadminusr
 public | django_migrations_id_seq | sequence | tintometricoadminusr
 public | django_session | table | tintometricoadminusr
 public | user | table | tintometricoadminusr
 public | user_groups | table | tintometricoadminusr
 public | user_groups_id_seq | sequence | tintometricoadminusr
 public | user_user_permissions | table | tintometricoadminusr
 public | user_user_permissions_id_seq | sequence | tintometricoadminusr
(18 rows)

tintometricoadmin=> 

```

> What if you open the regular Django shell and try to run the query? (`PaintColor.objects.all()`)

Same behavior:

```auto
(.venv) .venv ❯ ./manage.py shell
Python 3.13.1 (v3.13.1:06714517797, Dec 3 2024, 14:00:22) [Clang 15.0.0 (clang-1500.3.9.4)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from apps.acotone.models import PaintColor
>>> PaintColor.objects.all()
[DEBUG] [none] 2025-03-29 20:14:29,406 - apps.acotone.routers:db_for_read:37 - LegacyRouter.db_for_read model: <class 'apps.acotone.models.PaintColor'>
[DEBUG] [none] 2025-03-29 20:14:29,406 - apps.acotone.routers:db_for_read:40 - LegacyRouter model._meta.app_label: acotone
Traceback (most recent call last):
  File "/Users/alexandremjacques/Development/Projects/Python/tintometrico_admin/.venv/lib/python3.13/site-packages/django/db/backends/utils.py", line 105, in _execute
    return self.cursor.execute(sql, params)
           ~~~~~~~~~~~~~~~~~~~ ^^^^^^^^^^^^^
  File "/Users/alexandremjacques/Development/Projects/Python/tintometrico_admin/.venv/lib/python3.13/site-packages/psycopg/cursor.py", line 97, in execute
    raise ex.with_traceback(None)
psycopg.errors.UndefinedTable: relation "PaintColor" does not exist
LINE 1: ...ntColor"."colorOrder", "PaintColor"."status" FROM "PaintColo...
                                                             ^

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/Users/alexandremjacques/Development/Projects/Python/tintometrico_admin/.venv/lib/python3.13/site-packages/django/db/models/query.py", line 376, in __repr__
    data = list(self[: REPR_OUTPUT_SIZE + 1])
  File "/Users/alexandremjacques/Development/Projects/Python/tintometrico_admin/.venv/lib/python3.13/site-packages/django/db/models/query.py", line 400, in __iter__
    self._fetch_all()
    ~~~~~~~~~~~~~~~ ^^
  File "/Users/alexandremjacques/Development/Projects/Python/tintometrico_admin/.venv/lib/python3.13/site-packages/django/db/models/query.py", line 1928, in _fetch_all
    self._result_cache = list(self._iterable_class(self))
                         ~~~~ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/alexandremjacques/Development/Projects/Python/tintometrico_admin/.venv/lib/python3.13/site-packages/django/db/models/query.py", line 91, in __iter__
    results = compiler.execute_sql(
        chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size
    )
  File "/Users/alexandremjacques/Development/Projects/Python/tintometrico_admin/.venv/lib/python3.13/site-packages/django/db/models/sql/compiler.py", line 1574, in execute_sql
    cursor.execute(sql, params)
    ~~~~~~~~~~~~~~ ^^^^^^^^^^^^^
  File "/Users/alexandremjacques/Development/Projects/Python/tintometrico_admin/.venv/lib/python3.13/site-packages/django/db/backends/utils.py", line 122, in execute
    return super().execute(sql, params)
           ~~~~~~~~~~~~~~~ ^^^^^^^^^^^^^
  File "/Users/alexandremjacques/Development/Projects/Python/tintometrico_admin/.venv/lib/python3.13/site-packages/django/db/backends/utils.py", line 79, in execute
    return self._execute_with_wrappers(
           ~~~~~~~~~~~~~~~~~~~~~~~~~~~ ^
        sql, params, many=False, executor=self._execute
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    )
    ^
  File "/Users/alexandremjacques/Development/Projects/Python/tintometrico_admin/.venv/lib/python3.13/site-packages/django/db/backends/utils.py", line 92, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "/Users/alexandremjacques/Development/Projects/Python/tintometrico_admin/.venv/lib/python3.13/site-packages/django/db/backends/utils.py", line 100, in _execute
    with self.db.wrap_database_errors:
         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/alexandremjacques/Development/Projects/Python/tintometrico_admin/.venv/lib/python3.13/site-packages/django/db/utils.py", line 91, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "/Users/alexandremjacques/Development/Projects/Python/tintometrico_admin/.venv/lib/python3.13/site-packages/django/db/backends/utils.py", line 105, in _execute
    return self.cursor.execute(sql, params)
           ~~~~~~~~~~~~~~~~~~~ ^^^^^^^^^^^^^
  File "/Users/alexandremjacques/Development/Projects/Python/tintometrico_admin/.venv/lib/python3.13/site-packages/psycopg/cursor.py", line 97, in execute
    raise ex.with_traceback(None)
django.db.utils.ProgrammingError: relation "PaintColor" does not exist
LINE 1: ...ntColor"."colorOrder", "PaintColor"."status" FROM "PaintColo...

```

> If that doesn’t work, what happens then if you then run that query with the `using` clause?

Also, same issue.

```auto
(.venv) .venv ❯ ./manage.py shell
Python 3.13.1 (v3.13.1:06714517797, Dec 3 2024, 14:00:22) [Clang 15.0.0 (clang-1500.3.9.4)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from apps.acotone.models import PaintColor
>>> PaintColor.objects.using('legacy').all()
Traceback (most recent call last):
  File "/Users/alexandremjacques/Development/Projects/Python/tintometrico_admin/.venv/lib/python3.13/site-packages/django/db/backends/utils.py", line 105, in _execute
    return self.cursor.execute(sql, params)
           ~~~~~~~~~~~~~~~~~~~ ^^^^^^^^^^^^^
  File "/Users/alexandremjacques/Development/Projects/Python/tintometrico_admin/.venv/lib/python3.13/site-packages/psycopg/cursor.py", line 97, in execute
    raise ex.with_traceback(None)
psycopg.errors.UndefinedTable: relation "PaintColor" does not exist
LINE 1: ...ntColor"."colorOrder", "PaintColor"."status" FROM "PaintColo...
                                                             ^

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/Users/alexandremjacques/Development/Projects/Python/tintometrico_admin/.venv/lib/python3.13/site-packages/django/db/models/query.py", line 376, in __repr__
    data = list(self[: REPR_OUTPUT_SIZE + 1])
  File "/Users/alexandremjacques/Development/Projects/Python/tintometrico_admin/.venv/lib/python3.13/site-packages/django/db/models/query.py", line 400, in __iter__
    self._fetch_all()
    ~~~~~~~~~~~~~~~ ^^
  File "/Users/alexandremjacques/Development/Projects/Python/tintometrico_admin/.venv/lib/python3.13/site-packages/django/db/models/query.py", line 1928, in _fetch_all
    self._result_cache = list(self._iterable_class(self))
                         ~~~~ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/alexandremjacques/Development/Projects/Python/tintometrico_admin/.venv/lib/python3.13/site-packages/django/db/models/query.py", line 91, in __iter__
    results = compiler.execute_sql(
        chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size
    )
  File "/Users/alexandremjacques/Development/Projects/Python/tintometrico_admin/.venv/lib/python3.13/site-packages/django/db/models/sql/compiler.py", line 1574, in execute_sql
    cursor.execute(sql, params)
    ~~~~~~~~~~~~~~ ^^^^^^^^^^^^^
  File "/Users/alexandremjacques/Development/Projects/Python/tintometrico_admin/.venv/lib/python3.13/site-packages/django/db/backends/utils.py", line 122, in execute
    return super().execute(sql, params)
           ~~~~~~~~~~~~~~~ ^^^^^^^^^^^^^
  File "/Users/alexandremjacques/Development/Projects/Python/tintometrico_admin/.venv/lib/python3.13/site-packages/django/db/backends/utils.py", line 79, in execute
    return self._execute_with_wrappers(
           ~~~~~~~~~~~~~~~~~~~~~~~~~~~ ^
        sql, params, many=False, executor=self._execute
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    )
    ^
  File "/Users/alexandremjacques/Development/Projects/Python/tintometrico_admin/.venv/lib/python3.13/site-packages/django/db/backends/utils.py", line 92, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "/Users/alexandremjacques/Development/Projects/Python/tintometrico_admin/.venv/lib/python3.13/site-packages/django/db/backends/utils.py", line 100, in _execute
    with self.db.wrap_database_errors:
         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/alexandremjacques/Development/Projects/Python/tintometrico_admin/.venv/lib/python3.13/site-packages/django/db/utils.py", line 91, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "/Users/alexandremjacques/Development/Projects/Python/tintometrico_admin/.venv/lib/python3.13/site-packages/django/db/backends/utils.py", line 105, in _execute
    return self.cursor.execute(sql, params)
           ~~~~~~~~~~~~~~~~~~~ ^^^^^^^^^^^^^
  File "/Users/alexandremjacques/Development/Projects/Python/tintometrico_admin/.venv/lib/python3.13/site-packages/psycopg/cursor.py", line 97, in execute
    raise ex.with_traceback(None)
django.db.utils.ProgrammingError: relation "PaintColor" does not exist
LINE 1: ...ntColor"."colorOrder", "PaintColor"."status" FROM "PaintColo...
                                                             ^

```

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [March 29, 2025, 10:40pm UTC](https://forum.djangoproject.com/t/table-relation-cannot-be-found-on-postgres/40006/9 "2025-03-29T22:40:30Z")

</div>

> [@alexandremjacques](#):
>
> `(.venv) .venv ❯ ./manage.py dbshell`

This is showing you your default database. You would need to use the `--database` parameter to connect to the legacy database.

Also, once you’re connected and can verify that you see a table named “PaintColor”, issue a query to retrieve data from that table. (It doesn’t have to be everything. `select * from PaintColor limit 1;` would be sufficient. All you’re looking to determine is that Django can see and access that table.)

---

<div class="post-metadata">

**Author:** ![white-seolpyo](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/white-seolpyo/32/22386_2.png) [@white-seolpyo](https://forum.djangoproject.com/u/white-seolpyo)\
**Post date:** [March 31, 2025, 12:48am UTC](https://forum.djangoproject.com/t/table-relation-cannot-be-found-on-postgres/40006/10 "2025-03-31T00:48:49Z")

</div>

i think you do not migrate multiple database.  
If you have set up multiple databases, you must perform migration for each database.

```auto
# migrate default database
$ python manage.py migrate
# migrate additinal database
$ python manage.py migrate --database={DATABASES key}

```

---

<div class="post-metadata">

**Author:** ![alexandremjacques](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/alexandremjacques/32/893_2.png) [@alexandremjacques](https://forum.djangoproject.com/u/alexandremjacques)\
**Post date:** [April 7, 2025, 12:52pm UTC](https://forum.djangoproject.com/t/table-relation-cannot-be-found-on-postgres/40006/11 "2025-04-07T12:52:27Z")

</div>

Hi! I’m very embarassed to say that I found the issue: it was the wrong database URL registered in the LEGACY\_DATABASE\_URL env variable.

Sorry for taking everyone’s time.
