我有一个AbstractModel
,Model
和DraftModel
。
我需要DraftModel
才能从AbstractModel
继承,但是所有inherited
字段都应该是null=True
。我无法将Model
字段更改为null=True
,因为基于此的逻辑太多。
我不希望手动覆盖所有字段。
我尝试过:
def __init__(self,*args,**kwargs):
super().__init__(*args,**kwargs)
for field in self._meta.fields:
field.null = True
哪个不起作用,你有什么主意吗?
编辑
我想出了一种解决方案(检查我的答案),但是您愿意添加您的解决方案。
答案 0 :(得分:2)
在__init__
内更改字段无效,因为没有通话。
在DrafModel
下添加此代码段即可:
for field in DraftModel._meta.fields:
field.null = True
当然,您应该排除PrimaryKey
或BooleanField
之类的字段
编辑
对我来说,这可行:
for field in DraftModel._meta.fields:
if not field.primary_key and not isinstance(field, models.BooleanField):
field.null = True
答案 1 :(得分:0)
您可以覆盖__call__
方法:
class DraftModel(SomeAbstractModel):
def __call__(self, *args, **kwargs):
for f in self.__class__._meta.fields:
if f.name not in ['id'] and not isinstance(f, models.BooleanField): # copy pasted from your answer
f.null = True
super(DraftModel, self).__call__(*args, **kwargs)