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属性,我不想增加或者任何内容,请问我应该怎样做呢?

元芳怎么了
浏览 714回答 3
3回答

喵喵时光机

两种写法: 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)

米脂

你可以将那2个属性忽略不写,默认会自动继承父类的东西,只是模型model哪里改成你要的模型。

翻阅古今

class SubCommentForm(BlogCommentForm): class Meta(BlogCommentForm.Meta): # SubComment也是继承自BlogComment model = SubComment 不知道这样行不行
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python