How can I make a Django model read-only?

后端 未结 3 1666
后悔当初
后悔当初 2021-02-01 19:47

Is it possible to make a Django model read only? No creating, updating etc.

N.B. this question is different to:

Make a Django model read-only? (this question all

3条回答
  •  遥遥无期
    2021-02-01 20:39

    Database Routers

    To take more precautions that your model is read-only, you can use the DATABASE_ROUTERS setting to disable writing on a per model basis:

    # settings.py
    DATABASE_ROUTERS = ('dbrouters.MyCustomRouter', )
    
    
    # dbrouters.py
    class MyCustomRouter(object):
        def db_for_write(self, model, **hints):
            if model == MyReadOnlyModel:
                raise Exception("This model is read only. Shame!")
             return None
    

    I would consider this an insurance policy, and not the primary way to solve the problem. Mikael's answer, for example, is great but doesn't cover all cases because some Django operations bypass delete and save methods.

    See Juan José Brown's answer in Django - how to specify a database for a model? for a more detailed description of using a database router.

    Setting permissions on database user

    However, even the database router approach seems to have loopholes, i.e. there are ways to send SQL from Django that bypasses your router code. To be absolutely sure of making something readonly, you should set the permissions on the database user. This question describes how to set up a readonly postgreql user, which could then be the database user set by Django in settings.DATABASES.

提交回复
热议问题