如何为Django的Model类制作set()
方法,该方法将为指定的字段设置值,然后保存对象,因此可以这样调用:
object.set(field_1 = 0, field_2 = 1)
代替此:
object.field_1 = 0
object.field_2 = 1
object.save()
答案 0 :(得分:1)
这里是通过代理类实现set()
方法:
class foo(models.Model)
...
class foo_proxy(foo)
class Meta:
proxy = True
def set(self, **kwargs):
for arg, val in kwargs.items():
setattr(self, arg, val)
self.save()
这里是抽象类:
class model(models.Model)
class Meta:
abstract = True
def set(self, **kwargs):
for arg, val in kwargs.items():
setattr(self, arg, val)
self.save()
class foo(model)
...