How can I make a Django model read-only?

我的梦境 提交于 2019-12-03 10:22:45

Override the save and delete methods for the model. How are you planning to add objects to your model?

def save(self, *args, **kwargs):
     return

def delete(self, *args, **kwargs):
     return

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 the database user set by Django in settings.DATABASES.

Througth this is very old question - it will be usefull: https://docs.djangoproject.com/en/dev/ref/models/options/#managed

If False, no database table creation or deletion operations will be performed for this >>>model. This is useful if the model represents an existing table or a database view that has >>>been created by some other means.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!