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

2021-10-17 13:27:38 发布

您现在位置:Python中文网/ 问答频道 /正文

对于django1.6,这是我的最后一段代码。逻辑是,如果用户不存在数据库对象,则转到“account\u add”添加帐户。我不想使用用户配置文件或修改用户对象直接为特定的问题,所以请不要建议这些。我想知道的是,这段代码是否写得很好,或者可以写得更好,效率更高?你知道吗

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"