Django:通过url传递模型对象名称

时间:2014-09-21 13:28:41

标签: python django

我希望将模型名称作为参数传递给views.py
但它并不是很好 请指导我如何做到这一点谢谢

当我去http://127.0.0.1:8000/filter/image/party/时 有错误说:

'unicode' object has no attribute 'objects'

但终端可以打印mm =' Party'

这是我的代码:

models.py:

class Party(models.Model):  
     ....
class Fun(models.Model):  
     .... 

urls.py:

urlpatterns = patterns('',
    url(r'^image/(?P<model>\w+)/$', views.object_list_1 ),

views.py:

def object_list_1(request, model):
    mm =  model.capitalize()
    obj_list = mm.objects.all()        
    template_name = 'filterimgs/%s_list.html' % mm.lower()
    return render_to_response(template_name, {'object_list': obj_list, 
                          context_instance=RequestContext(request))

2 个答案:

答案 0 :(得分:3)

不确定为什么你认为这会起作用:只是在字符串上调用capitalize()并不会神奇地将它转换为模型类。

您需要在Django的模型注册表中按名称查找实际的类。幸运的是,有一个功能:get_model

from django.db.models.loading import get_model
cls = get_model(app_name, model)
obj_list = cls.objects.all() 

答案 1 :(得分:0)

您应该将model名称映射到模型类。

一种方法是使用getattr从app模块中获取模型实例。

from app_name import models

def object_list_1(request, model):
    mm =  model.capitalize()
    cls = getattr(models, mm)
    obj_list = cls.objects.all()
    template_name = 'filterimgs/%s_list.html' % mm.lower()
    return render_to_response(template_name, {'object_list': obj_list,
                          context_instance=RequestContext(request))

或使用显式映射:

name_to_model_class = {'Party': Party, 'Fun': Fun}

def object_list_1(request, model):
    mm =  model.capitalize()
    cls = name_to_model_class[mm]
    obj_list = cls.objects.all()
    template_name = 'filterimgs/%s_list.html' % mm.lower()
    return render_to_response(template_name, {'object_list': obj_list,
                          context_instance=RequestContext(request))