Make a Django model read-only?

前端 未结 4 1689
感情败类
感情败类 2021-01-08 00:21

What it says on the tin. Is there a way to make a Django model read-only?

By this I mean a Django model in which once records have been created, they can\'t be edite

4条回答
  •  粉色の甜心
    2021-01-08 01:08

    You can override the model's save method and check whether it's an existing entity, in which case you won't save any changes:

    def save(self, *args, **kwargs):
        if self.id is None:
            super(ModelName, self).save(*args, **kwargs)
    

    So in this example you only save the changes when the entity has not got an id yet, which is only the case when it's a new entity that hasn't been inserted yet.

提交回复
热议问题