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

这是因为每种方法都依赖于用户。有没有办法将它提取到我的模型或干燥的东西中,所以我不需要在每种方法中重复自己?

4

2 回答 2

2

Why don't you write a service function? Or decorate your functions with a user object if available?

services.py

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

and

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 回答