Question

I'm finding myself with a django project handling two distinct classes mapped on a similar table name:

class BarA(models.Model):
[...]
class Meta:
    db_table = 'bar' # doesn't specify any schema

class BarB(models.Model):
[...]
class Meta:
    db_table = u'foo"."bar'

The project is using a database containing two schemas: public and foo.

The way this application is templated and deployed makes things even more confusing: on some servers, django connects to database with the user "John", not member of any role, but on other servers it connects with user "Eric", member of a foo role.

Two questions here:

  1. If django's meta class doesn't mention any specific schema, how does Postgres decide which table it will work with ? So far, it appears that user Eric will always hit the foo.bar table, and never the public.bar one, regardless of the called class. With user "John", I'm only using BarA class and it properly hits public.bar.
  2. Django doesn't seem to handle schemas; is this solution considered as a good practice for that kind of case (please note that I cannot rename the existing tables)?
Was it helpful?

Solution

In postgres search_path variable set the priority for choosing the schema for the table:

search_path (string)
This variable specifies the order in which schemas are searched when an object (table, data type, function, etc.) is referenced by a simple name with no schema specified. When there are objects of identical names in different schemas, the one found first in the search path is used.
[...]
The current effective value of the search path can be examined via the SQL function current_schemas.

A quick way to do so:

SELECT current_schemas(True);

You can find details on how to manage search_path in section 5.7.3. of this article: http://www.postgresql.org/docs/current/static/ddl-schemas.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top