Django模型:如何使用mixin类覆盖django模型的功能喜欢保存 [英] Django Model: How to use mixin class to override django model for function likes save
本文介绍了Django模型:如何使用mixin类覆盖django模型的功能喜欢保存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在每个模型保存之前验证值。所以我必须覆盖保存功能。
代码几乎是一样的,我想把它写入一个mixin类。但是
失败我不知道如何写超级功能。
I want to validate value before every model save. So, I must override the save function. The code is nearly just the same on, and I want to write it in a mixin class. But failed for I don't know how to write super func.
我很不好意思,很抱歉。
I'm poor of of English, so sorry.
class SyncableMixin(object):
def save(self, *args, **kwargs):
try:
res = validate(*args, **kwargs)
except Exception:
raise ValidateException()
super(?, self).save(*args, **kwargs)
class SomeModel(SyncableMixin, models.Model):
pass
推荐答案
你总是在超级调用中引用当前类。
You always refer to the current class in a super call.
super(SyncableMixin, self).save(*args, **kwargs)
对于mixins以及正常的子类化,这是正确的。
This is true for mixins as well as normal subclassing.
(另外,捕获一个基地异常,特别是不要只抓住东西来提高另一个异常 - 这根本就没有意义。)
(Also, don't catch a base Exception, and especially don't catch things only to raise another Exception - that makes no sense at all.)
这篇关于Django模型:如何使用mixin类覆盖django模型的功能喜欢保存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文