冗余的django代码

时间:2013-01-29 00:59:31

标签: python django django-views django-generic-views

我有一些我编写的代码,它的目的完全正常。

from django.shortcuts import get_object_or_404
from django.views.generic import ListView
from cab.models import Language

class LanguageDetail(ListView):


    def get_queryset(self):
        slug = self.kwargs['slug']
        language = get_object_or_404(Language, slug=slug)
        return language.snippet_set.all()

    paginate_by = 20
    template_name = 'cab/language_detail.html'

    def get_context_data(self, **kwargs):
        slug = self.kwargs['slug']
        language = get_object_or_404(Language, slug=slug)
        context = super(LanguageDetail, self).get_context_data(**kwargs)
        context['language'] = language
        return context

我的问题是我在两个函数中重复了两行代码,我不喜欢这样。

slug = self.kwargs['slug']
language = get_object_or_404(Language, slug=slug)

我怎么能避免? 提前谢谢。

1 个答案:

答案 0 :(得分:0)

你的意思是这样吗?

def get_slug(self, name):   
    slug = self.kwargs[name]
    return get_object_or_404(Language, slug=slug)

可以用作language = self.get_slug('slug')

请记住,如果kwargs不包含name,则会抛出错误。为了防止这种情况,您可以执行以下操作:

slug = self.kwargs.get(name, None)
if slug is not None:
    ...