登录

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

# Python
高洛峰 高洛峰 2710 天前 885 次浏览

全部回复(2) 我要回复

  • 欧阳克

    欧阳克2016-11-16 14:05:01

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

    回复
    0
  • 三叔

    三叔2016-11-16 14:04:49

    两种写法:

    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)


    回复
    0
  • 取消 回复 发送