[Solved]-Specifying Readonly access for Django.db connection object



Man, once again, I should read the docs more carefully before I post questions here. I can define a readonly connection to my production database in the settings file, and then straight from the docs:

If you are using more than one database, you can use django.db.connections to obtain the connection (and cursor) for a specific database. django.db.connections is a dictionary-like object that allows you to retrieve a specific connection using its alias:

from django.db import connections
cursor = connections['my_db_alias'].cursor()
# Your code here...


    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'mydb',
        'USER': 'myusername',
        'PASSWORD': 'mypassword',
        'HOST': 'myhost',
        'OPTIONS': {
            'options': '-c default_transaction_read_only=on'

Source: https://nejc.saje.info/django-postgresql-readonly.html



You can achieve this by hooking into Django’s connection_created signal, and
then making the transaction read-only.

The following works for PostgreSQL:

from django.db.backends.signals import connection_created

class MyappConfig(AppConfig):
    def ready(self):
        def connection_created_handler(connection, **kwargs):
            with connection.cursor() as cursor:
                cursor.execute('SET default_transaction_read_only = true;')
        connection_created.connect(connection_created_handler, weak=False)

This can be useful for some specific Django settings (e.g. to run development
code with runserver against the production DB), where you do not want to
create a real read-only DB user.



If you add a serializer for you model, you could specialized in the serializer that is working in readonly mode

class AccountSerializer(serializers.ModelSerializer):
    class Meta:
        model = Account
        fields = ('id', 'account_name', 'users', 'created')
        read_only_fields = ('account_name',)

from http://www.django-rest-framework.org/api-guide/serializers/#specifying-read-only-fields


Leave a comment