How can I make a model read-only?

2019-03-25 00:18发布

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 allows creation of new records)

Whole model as read-only (only concerns the Django admin interface - I'd like the model to be read only throughout the whole app)

3条回答
冷血范
2楼-- · 2019-03-25 00:49

To be absolutely sure 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.

查看更多
干净又极端
3楼-- · 2019-03-25 00:52

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
查看更多
smile是对你的礼貌
4楼-- · 2019-03-25 01:07

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.

查看更多
登录 后发表回答