django - python中怎么override父类的class Meta?
本文介绍了django - python中怎么override父类的class Meta?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
这是我的一个父类
class BlogCommentForm(forms.ModelForm):
class Meta:
model = BlogComment
fields = ['user_name', 'body']
widgets = {
'user_name': forms.TextInput(attrs={
'required': 'required',
# ...还有很多其他属性
}),
'body': forms.Textarea(attrs={
'required': 'required',
# ...还有很多其他属性
}),
}
这是我的子类
class SubCommentForm(BlogCommentForm):
class Meta:
# SubComment也是继承自BlogComment
model = SubComment
fields = ['user_name', 'body']
widgets = {
'user_name': forms.TextInput(attrs={
'required': 'required',
# ...还有很多其他属性
}),
'body': forms.Textarea(attrs={
'required': 'required',
# ...还有很多其他属性
}),
}
现在我想简化一下代码,因为我的SubComment也是继承自BlogComment,所以对于SubCommentForm这个子类我只想让下model = SubComment,对于fields和widgets属性,我不想增加或者任何内容,请问我应该怎样做呢?
解决方案
两种写法:
import copy
class A:
class Meta:
model = 'hello'
fields = ['a', 'b']
widgets = {'a': 'b'}
class B(A):
"""第一种"""
dic = copy.deepcopy({
k: v
for (k, v) in A.Meta.__dict__.items()
if not k.startswith('__')
})
dic['model'] = 'b'
Meta = type('Meta', (object,), dic)
class C(A):
"""第二种"""
class Meta:
model = 'c'
widgets = copy.deepcopy(A.Meta.widgets)
fields = copy.deepcopy(A.Meta.fields)
这篇关于django - python中怎么override父类的class Meta?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文