使Django模型只读? [英] Make a Django model read-only?
本文介绍了使Django模型只读?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这样我就是一个Django模型,其中一旦创建了记录,就不能编辑它们。
这对于记录事务历史记录的模型非常有用。
解决方案
您可以覆盖模型的保存方法,并检查它是否是现有实体,在这种情况下,您将不会保存任何更改:
def save(self,* args,** kwargs):
if self.id is None:
超(ModelName,self).save(* args,** kwargs)
所以在这个例子你只有在实体还没有得到一个 id
的时候才保存这些变化,只有当它还没有被插入的新实体时才是这样。 p>
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 edited.
This would be useful for a model that records transaction history.
解决方案
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.
这篇关于使Django模型只读?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文