【问题标题】:Get parameters of object in metaclass of this object获取该对象元类中对象的参数
【发布时间】:2011-04-24 09:55:15
【问题描述】:

我的问题是 python/django 混合。我有一个将显示一些字段的表单模型。根据此模型的某些参数,发送到创建此对象的元类的数据应该不同。但是,在 Meta 的主体内,我怎样才能达到这个参数呢?我应该使用一些全局变量而不是对象参数(因为它只是为了临时存储值而引入的)?

class MyForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)   
        instance = kwargs.get("instance")
        self.type = None
        try:
            type = self.instance.template_id
        except:
            pass

    class Meta:
        model = ContentBase
        fields = ["title", "slug", "description", "text", "price",]

        #here I need to have the value of 'type'
        if type != 2:
            try:
                fields.remove("price")
            except:
                pass

【问题讨论】:

    标签: python django scope metaclass


    【解决方案1】:

    你不能在 Meta 中做任何动态的事情。这不是它的用途。

    为什么不能在__init__ 内完成所有操作?您可以从那里修改self.fields

    【讨论】:

      【解决方案2】:

      正如丹尼尔提议的那样,我将整个事情转移到__init__

          type = None
          try:
              type = self.instance.template_id
          except:
              pass
      
          if type != 2:
              self.fields.pop("price")
          else:
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-18
        • 1970-01-01
        • 1970-01-01
        • 2010-12-21
        • 1970-01-01
        相关资源
        最近更新 更多