Django动态类

2024-09-19 23:45:34 发布

您现在位置:Python中文网/ 问答频道 /正文

这两种方法是等价的。在

方法1

class X(object):
    a = 1

方法2

^{pr2}$

我想知道什么是等效的:

class ObjectTable(tables.ModelTable):

    id = tables.Column(sortable=False, visible=False)
    societe = tables.Column(sortable=False, visible=False)

    class Meta:
        model = models.get_model('core', "Fournisseur")

我试过了但没用:

ObjectTable=type('ObjectTable',(tables.ModelTable,),dict(model=myModel))
ObjectTable=type('ObjectTable',(tables.ModelTable,),dict(meta.model=myModel))
ObjectTable=type('ObjectTable',(tables.ModelTable,),dict(meta=myModel))

谢谢。在


Tags: 方法falsetablesmodeltypecolumndictmeta
3条回答

它与django示例中的值完全相同。你自己试试吧。在

您的所有示例都如您所说“不起作用”,因为(a)除了meta(b)不创建任何其他应拼写为Meta的字段(c)Meta的值应该是一个(旧样式)类。在

解决方法如下:

def CreateForm(for_model, request=None, instance=None, user=None):
    class _StateMachineBaseModelForm(ModelForm):
        class Meta:
            model = for_model
            exclude = ('societe',)

        def __init__(self, *args, **kwargs):
            super(_StateMachineBaseModelForm, self).__init__(*args, **kwargs)
            try:
                if user:
                    self.fields['banque'].queryset = Banque.objects.filter(pays=user.get_profile().societe.pays)
            except:
                pass

    if for_model: return _StateMachineBaseModelForm(request, instance=instance)

在开始之前,我同意S.Lott的评论。你几乎肯定不想这么做。在

接下来是:

# You can't create an old-style class with type,
# so define a function that creates one.
def make_meta_class():
    class Meta:
        model = models.get_model('core', "Fournisseur")
    return Meta

# Create the dictionary (remember to include the fields as well as the meta class)
d=dict(,
    Meta=make_meta_class(),
    id=tables.Column(sortable=False, visible=False)
    societe=tables.Column(sortable=False, visible=False)
)
# Create the class dynamically
ObjectTable=type('ObjectTable', (tables.ModelTable,), d)

相关问题 更多 >