[Solved]-How to find Postgres version from Django?

14👍

Get a database connection:

from django.db import connection

And access the inner psycopg2 connection object:

print(connection.cursor().connection.server_version)

One-liner:

$ python3 manage.py shell -c "from django.db import connection; print(connection.cursor().connection.server_version)"
90504

After Postgres 10, the number is formed by multiplying the server’s major version number by 10000 and adding the minor version number. For example, version 10.1 will be returned as 100001, and version 11.0 will be returned as 110000. Zero is returned if the connection is bad.

Prior to Postgres 10, the number is formed by converting the major, minor, and revision numbers into two-decimal-digit numbers and appending them together. For example, version 8.1.5 will be returned as 80105.

Therefore, for purposes of determining feature compatibility, applications should divide the result of connection.server_version by 100 not 10000 to determine a logical major version number. In all release series, only the last two digits differ between minor releases (bug-fix releases).

Docs:

https://www.psycopg.org/docs/connection.html#connection.server_version

https://www.postgresql.org/docs/current/libpq-status.html#LIBPQ-PQSERVERVERSION

Leave a comment