0

可能重复:
django:使用字符串选择特定模型

示例:(Django,views.py)

def create(request, mod):  
    #mod is a modelname    
    if request.method == 'POST':  
        form = globals()[mod+"Form"](request.POST)  
        if form.is_valid():  
            new_file_num = form.save(commit=False)  
            >>>> if entry.objects.filter(fileTypeNumber=1).exists():  

我的问题就在这里。

if entry.objects.filter( ....

相反,我想:

mod = entry;  
if mod.objects.filter( ....  

这里的总体目标是为具有不同字段的多个模型使用相同的“视图”。有一个更好的方法吗?该视图本质上是分配一个文件编号,然后保存它。

提前致谢

4

2 回答 2

0

从实例中拉出类。

mod = my_instance.__class__
if mod.objects.filter(fileTypeNumber=1).exists():
于 2013-02-02T20:05:49.237 回答
0

You could maybe do something like:

from models import Foo, Bar

def create_view(model):
    # model is the actual model class (not instance)
    def view(request):
        form = globals()[model.__name__ + "Form"]
        if model.objects.filter(fileTypeNumber=1).exists():
            pass
            # whatever you do with it
    return view

foo_view = create_view(Foo)
bar_view = create_view(Bar)

This would make two views for the Foo and Bar models. But if you've got different fields for each model (or if you're validating or doing anything else that needs handling differently), you may be better off just making different views by hand for each one instead of doing this kind of abstract creation function.

于 2013-02-02T20:09:32.937 回答