干我的意见

时间:2012-04-21 20:59:01

标签: django django-models

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

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

2 个答案:

答案 0 :(得分: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 :(得分: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)