1

私のviews.pyにはこの醜いパターンがあり、私のビューのほとんどすべてのメソッドは

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() 

これは、すべてのメソッドがユーザーに依存しているためです。これを私のモデルまたは何かDRYに抽出して、すべての方法で繰り返す必要がないようにする方法はありますか?

4

2 に答える 2

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 ...
于 2012-04-21T21:18:37.753 に答える
1

クラスベースのジェネリックビューを使用し、共通コードを基本クラスのメソッドに配置します。このようなもの:

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)
于 2012-04-21T21:57:17.007 に答える