django - python中怎么override父类的class Meta?

 海带木耳求_529 发布于 2022-10-26 15:00

这是我的一个父类

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

3 个回答
  • class SubCommentForm(BlogCommentForm):
    
        class Meta(BlogCommentForm.Meta):
            # SubComment也是继承自BlogComment
            model = SubComment
    

    不知道这样行不行

    2022-10-27 01:15 回答
  • 你可以将那2个属性忽略不写,默认会自动继承父类的东西,只是模型model哪里改成你要的模型。

    2022-10-27 01:15 回答
  • 两种写法:

    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)
    2022-10-27 01:15 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有