0

我想使用基于类的视图创建一个等效的“method_splitter”,以便删除我的 URL confs 中的一些硬编码。

我想要以下网址:

ListView: http://mysite.com/<model_name>/
DetailView: http://mysite.com/<model_name>/<field_value>/

ListView 的查询将是:

<model_name>.objects.all()

DetailView 的查询集将是:

<model_name>.objects.get(<field>=<field_Value>)

目前,我的观点是由于 url conf 中的一些硬编码而起作用的,但我想找到一个可以扩展的优雅解决方案。

我的解决方案没有给出 404,但什么也不显示:

视图.py

class ListOrDetailView(View):

def __init__(self, **kwargs):
    for key, value in kwargs.iteritems():
        setattr(self, key, value)

try: #If/Else instead?
    def goToDetailView(self, **kwargs):
        m = get_list_or_404(self.kwargs['model']) #Is this even needed?
        return DetailView(model=self.kwargs['model'], slug=self.kwargs['slug'], template_name='detail.html', context_object_name='object')

except: #If/Else instead?
    def goToListView(self, **kwargs):
        q = get_object_or_404(self.kwargs['model'], slug=self.kwargs['slug']) #Is this even needed?
        return ListView(model=self.kwargs['model'], template_name='list.html', context_object_name='object_list',) 

MyApp 的 urls.py

url(r'^(?P<model>[\w]+)/?(?P<slug>[-_\w]+)/$', ListOrDetailView.as_view()),
4

1 回答 1

0

As limelights said, this is a horrible design pattern; the whole point of Django is separation of models and views. If you fear that you might have to write a lot of repetitive code to cover all your different models, trust me that it's not much of an issue with class-based views. Essentially, you need to write this for each of your models you wish to expose like this:

Urls.py:

urlpatterns = patterns('',
    url(r'^my_model/$', MyModelListView.as_view(), name="mymodel_list"),
    url(r'^my_model/(?P<field_value>\w+)/$', MyModelDetailView.as_view(), name="mymodel_detail"),
)

views.py:

from django.views.generic import ListView, DetailView

class MyModelListView(ListView):
    model = MyModel


class MyModelDetailView(DetailView):
    model = MyModel

    def get_queryset(self):
        field_value = self.kwargs.get("field_value")
        return self.model.objects.filter(field=field_value)
于 2013-03-28T19:43:50.417 回答