2012-04-21 6 views
1

をアップDRY'ing私は私の意見では、ほぼすべての方法は、これが原因で、すべてのメソッドである私の見解

Products.objects.active().filter(user=request.user) # Return all products for the current user

または

user = get_object_or_404(User, user=request.user) 
products = user.product_set.all() 

で構成され、私のviews.pyでこの醜いパターンを持っていますユーザーに依存します。これを私のモデルやDRYに抽出する方法はありますか?あらゆる方法で自分自身を繰り返す必要はありませんか?

答えて

2

なぜサービス機能を書いていないのですか?または、利用可能な場合はユーザーオブジェクトで関数を飾りますか?

services.py 

def get_products(request, *args, **kwargs): 
    user = request.user 
    return somethings **depending** on the arguments passed... 

views.py 

def someview(request): 
    context['user_products'] = services.get_products(request, commonCase) 
    render ... 
1

使用class-based generic viewsと、基本クラスのメソッドで共通のコードを置きます。このようなもの:

from django.contrib.auth.decorators import login_required 
from django.utils.decorators import method_decorator 
from django.views import generic 

class UserView(generic.View): 
    """ 
    A generic view which requires an authenticated user and shows only 
    active products belonging to that user. 
    """ 

    def get_products(self): 
     """ 
     Return queryset of products belonging to the authenticated user. 
     """ 
     return self.request.user.product_set.all() 

    @method_decorator(login_required) 
    def dispatch(self, *args, **kwargs): 
     return super(UserView, self).dispatch(*args, **kwargs) 
関連する問題