Back to all reviewers

Use connection by alias

django/django
Based on 6 comments
Python

When working with database operations in Django projects that might use multiple database backends, always access database features and operations through `connections[alias]` instead of the global `connection` object. This ensures your code works correctly regardless of which database backend is being used for a specific operation.

Database Python

Reviewer Prompt

When working with database operations in Django projects that might use multiple database backends, always access database features and operations through connections[alias] instead of the global connection object. This ensures your code works correctly regardless of which database backend is being used for a specific operation.

For example, instead of:

def db_returning(self):
    """Private API intended only to be used by Django itself."""
    return (
        self.has_db_default() and connection.features.can_return_columns_from_insert
    )

Use:

def db_returning(self):
    """Private API intended only to be used by Django itself."""
    return self.has_db_default()

And check the feature at the appropriate time with the correct connection:

if connections[using].features.can_return_columns_from_insert:
    # Perform operation with RETURNING clause

This approach prevents bugs in multi-database setups where features vary across backends, such as when the default database is MySQL but you’re also using PostgreSQL for specific operations.

6
Comments Analyzed
Python
Primary Language
Database
Category

Source Discussions