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

1πŸ‘

βœ…

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...
πŸ‘€alayers2

4πŸ‘

DATABASES = {
    '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

πŸ‘€guettli

3πŸ‘

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.

πŸ‘€blueyed

0πŸ‘

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

πŸ‘€anonymez

Leave a comment