django 在视图的final return子句中合并几个“context”块

mcdcgff0  于 2023-05-01  发布在  Go
关注(0)|答案(2)|浏览(91)

嗨,我已经搜索了这个,找到了类似的主题,但没有一个给我一个答案,似乎有帮助。或者我可能搜索了错误的术语。
现在我想知道,你是否可以选择性地合并一个“返回渲染”的上下文。...”命令。由于Django传播了一种“不要重复你自己”的哲学,我想修改下面的代码来缩短它(几个if子句与角色权限有关。...):

def show(request):

    now_day = datetime.date.today()
    current_user = request.user 

    if request.method == 'GET':

        if view_self(current_user) == True and more_rights(current_user) == False:
            if Employees.objects.filter(employee_number=current_user).exists():

                context = {'names': Employees.objects.filter(employee_number=current_user)}
            else:
                context = {'info': "Für sie existiert (noch) kein Datensatz in dieser Datenbank"}  
        else: 
            context = {'names': Employees.objects.all().order_by('last_name').values()}

        return render(request, 'show.html', context)

    else:
        if view_self(current_user) == True and more_rights(current_user) == False:

            if request.POST['id'] == 'Mitarbeiter auswählen...':
                context = {
                    'names': Employees.objects.filter(employee_number=current_user),
                    'info': "Bitte treffen Sie zuerst eine Auswahl"
                }
            else:
                employee = request.POST['id']
                context = {
                    'names': Employees.objects.filter(employee_number=current_user),
                    'entries': Employees.objects.filter(id=request.POST['id']),
                    'work_conditions': Employment.objects.filter(employee_id=request.POST['id']),
                    'functions': Functions.objects.filter(employee__functions=request.POST['id']).order_by('function'),
                    'fieldsoa': FieldsOfActivity.objects.filter(employee__fieldsofactivity=request.POST['id']).order_by('field_of_activity'),
                    'missions': Foreign_Missions.objects.filter(employee_id=request.POST['id']).order_by('-begin'),
                    'examinations': Examinations.objects.filter(employee_id=request.POST['id']).order_by('-date'),
                    'total_duration_days': Foreign_Missions.objects.total_duration_days(employee),
                    'today': now_day,
                    'special_header': "Datensätze anzeigen"
                }

        elif request.POST['id'] == 'Mitarbeiter auswählen...':
            context = {
            'names': Employees.objects.all().order_by('last_name').values(),
            'info': "Bitte treffen Sie zuerst eine Auswahl"
            }
    
        elif 'id' in request.POST:
            employee = request.POST['id']             #Employees.objects.get(pk=id)
            context = {
            'names': Employees.objects.all().order_by('last_name').values(),
            'entries': Employees.objects.filter(id=request.POST['id']),
            'work_conditions': Employment.objects.filter(employee_id=request.POST['id']),
            'functions': Functions.objects.filter(employee__functions=request.POST['id']).order_by('function'),
            'fieldsoa': FieldsOfActivity.objects.filter(employee__fieldsofactivity=request.POST['id']).order_by('field_of_activity'),
            'missions': Foreign_Missions.objects.filter(employee_id=request.POST['id']).order_by('-begin'),
            'examinations': Examinations.objects.filter(employee_id=request.POST['id']).order_by('-date'),
            'total_duration_days': Foreign_Missions.objects.total_duration_days(employee),
            'today': now_day,
            'special_header': "Datensätze anzeigen"
            }

        return render(request, 'show.html', context)

所以我的问题是我能不能以一种实用的方式“分割”上下文行,把每个对应的if子句中显示的部分放在靠近return render命令的位置,这样我就不必重复这些行了?
更新2023-04-28:尝试(使用另一个模块,更短的代码,更容易阅读)空上下文和逐步填充的方法。不会在这里工作:

def delete(request):

context = {}
context['names'] = Employees.objects.all().order_by('last_name').values(),

if request.method == 'GET':
    context = {
        # 'names': Employees.objects.all().order_by('last_name').values(),
        'special_header': "Datensätze löschen",
    }
    
# Wenn der Button ohne Auswahl gedrückt wird
elif 'id' in request.POST and request.POST['id'] == 'Mitarbeiter löschen...':
    context = {
        # 'names': Employees.objects.all().order_by('last_name').values(),
        'info': "Bitte treffen Sie zuerst eine Auswahl"
    }

else:
    id = request.POST['id']
    lastname = Employees.objects.get(id=id).last_name.upper()
    firstname = Employees.objects.get(id=id).first_name
    trash = Employees.objects.filter(id=id)
    # trash.delete()

    context = {
        # 'names': Employees.objects.all().order_by('last_name').values(),
        'success': "Datensatz für " + lastname + ", " + firstname + " wurde gelöscht"
    }

return render(request, 'delete.html', context)

在代码中留下了注解部分,以澄清我想做的事情

ie3xauqp

ie3xauqp1#

传递给render的上下文是一个python字典。不需要总是完整地定义它;可以逐步填充。你可以简单地从一个空的开始,然后在任何你想要的地方添加一个项目:

context = {}
context['key1']=xxxx
....
context['key2']=yyyy
...
...
render(request, "xyz.html", context)

更新:将项添加到上下文始终使用

context['key_n']=xyz

如果使用

context={
   'key_n': xyz
}

则创建新的上下文Dict并且丢失原始上下文。

rekjcdws

rekjcdws2#

非常可行,请遵循以下步骤:
1.将尽可能多的声明移到条件之上,然后根据需要添加到上下文字典中,或者通过条件重写上下文字典中的值
1.尽可能使用三元表达式优化代码
见下文,这应该工作:

def show(request):
    cur_user = request.user
    view_self_only = view_self(cur_user) and not more_rights(cur_user)
    
    if request.method == "GET":
        info = "Für sie existiert (noch) kein Datensatz in dieser Datenbank"
        if view_self_only:
            if Employees.objects.filter(employee_number=cur_user).exists():
                names = Employees.objects.filter(employee_number=cur_user)
                context = {"names": names}
            else:
                context = {"info": info}
        else:
            names = Employees.objects.all().order_by("last_name").values()
            context = {"names": names}
        return render(request, 'show.html', context)

    employee_filter = (
        Employees.objects.filter(employee_number=cur_user) 
        if view_self_only 
        else Employees.objects.all().order_by('last_name').values()
    )
    context = {'names': employee_filter}

    if request.method == 'POST':
        id = request.POST['id']
        if employee_id != 'Mitarbeiter auswählen...':
            employee = Employees.objects.filter(id=id)
            work_conditions = Employment.objects.filter(employee_id=id)
            functions = Functions.objects.filter(
                employee__functions=id).order_by('function')
            fieldsoa = FieldsOfActivity.objects.filter(
                employee__fieldsofactivity=id).order_by('field_of_activity')
            missions = Foreign_Missions.objects.filter(
                employee_id=id).order_by('-begin')
            examinations = Examinations.objects.filter(
                employee_id=id).order_by('-date')
            tot_dur_days = Foreign_Missions.objects.total_duration_days(id)
            context.update({
                'entries': employee,
                'work_conditions': work_conditions,
                'functions': functions,
                'fieldsoa': fieldsoa,
                'missions': missions,
                'examinations': examinations,
                'total_duration_days': tot_dur_days,
                'today': date.today(),
                'special_header': "Datensätze anzeigen"
            })
        else:
            context['info'] = "Bitte treffen Sie zuerst eine Auswahl"
    return render(request, 'show.html', context)

我对你的代码做了一些其他的轻微修改,使其符合PEP 8,但功能应该完全相同,现在只是更干净,更干。
希望这个工作!

相关问题