Make a Django model read-only?

前端 未结 4 1659
感情败类
感情败类 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:12

    You can override the save method and not call super if you wanted to. That'd be a fairly easy way of accomplishing this.

    # blatantly ripped the save from another answer, since I forgot to save original model
    def save(self, *args, **kwargs):
        if self.id is None:
            super(ModelName, self).save(*args, **kwargs)
    
    def delete(self, *args, **kwargs):
        return
    

    You should probably also raise an exception if a delete or update is attempting to occur instead of simply returning. You want to signal the user what is happening - that the behaviour isn't valid.

提交回复
热议问题