UpdateView和CreateView - 代码是高效还是可以改进?

时间:2014-03-13 14:00:37

标签: python django

对于Django 1.6,这是我的最终代码。逻辑是,如果用户不存在数据库对象,则转到' account_add'添加帐户。我不想使用user_profile或直接修改用户对象以解决特定问题,因此请不要提出建议。我想知道的是,如果这段代码写得好,或者写得更好,效率更高?

class AccountCreateOrModify():
    model = Employee
    form_class = AccountForm
    template_name = 'bot_data/account_modify.html'
    success_url = reverse_lazy('home')


class ViewEmployee(LoginRequiredMixin, 
        DetailView):

    model = Employee
    template_name = 'bot_data/employee_detail.html'

    def dispatch(self, request,
            *args, **kwargs):
        try:
            pk = self.request.user.pk
            queryset = self.model.objects.get(user_assigned=pk)
            return super(ViewEmployee, 
                    self).dispatch(request, 
                            *args, **kwargs)
        except Employee.DoesNotExist:
            return redirect('account_add')

    def get_object(self):
            user = self.request.user.id
            find_user = self.model.objects.get(id=user)
            return find_user

class AccountModify(LoginRequiredMixin, 
        AccountCreateOrModify,
        UpdateView):

    def dispatch(self, request,
            *args, **kwargs):
        try:
            pk = self.request.user.pk
            queryset = self.model.objects.get(user_assigned=pk)
            return super(AccountModify, 
                    self).dispatch(request, 
                            *args, **kwargs)
        except Employee.DoesNotExist:
            return redirect('account_add')

    def get_object(self, queryset=None):
        pk = self.request.user.pk
        queryset = self.model.objects.get(user_assigned=pk)
        return queryset





class AccountCreateRecord(LoginRequiredMixin,
        AccountCreateOrModify,
        CreateView):
    print "filler"

1 个答案:

答案 0 :(得分:1)

try块应该包含一行:

def dispatch(self, request, *args, **kwargs):
    pk = self.request.user.pk
    try:
        queryset = self.model.objects.get(user_assigned=pk)
    except Employee.DoesNotExist:
        return redirect('account_add')
    return super(ViewEmployee, self).dispatch(
        request, *args, **kwargs)

如果除了没有返回任何内容,请查找tryexceptelse块继承。

类应该从对象继承或没有括号:

class AccountCreateOrModify(object): # a bit better
    pass

class AccountCreateOrModify: # avoid useless parenthesis
    pass

如果Employee是一个抽象类,你可以避免命中数据库。

def get_object(self):
    user = self.request.user.id
    find_user = self.model.objects.get(id=user)
    return find_user

为什么"打印"在你上一堂课中,你知道pass(no-op)关键字吗?

class AccountCreateRecord(LoginRequiredMixin, AccountCreateOrModify,
                          CreateView):
    pass