理解 try except python/django

understanding try except python/django

我需要你的帮助来理解 try-except python/Django。

所以我有这个功能:

def submit_dept_head_application(request, application_id):
cv = request.FILES['cv']
letter = request.FILES['letter']
candidate_id = request.data['candidateId']
rank_id = request.data['requestedRankId']
application_state = {
    'candidate_id': candidate_id,
    'rank_id': rank_id,
    'cv_filename': cv.name,
    'letter_filename': letter.name,
}

creator = Profile.objects.get(user=request.user.id)
department = creator.department
applicant = Profile.objects.get(user=candidate_id)
applicant_profile_id = applicant.id
rank = Rank.objects.get(id=rank_id)

try:
    application = Application.objects.get(id=application_id)
    # TODO - update application
except Application.DoesNotExist:
    application = None

if application is None:
    application = Application(creator=creator, applicant=applicant, desired_rank=rank,
                              application_state=application_state, department=department
                              )
    application.save()
    create_application_directory(application.id)

ApplicationStep.objects.update_or_create(
    application=application, step_name=Step.STEP_1,
    defaults={'can_update': True, 'can_cancel': True, 'currentStep': True}
)

copy_to_application_directory(cv, application.id)
copy_to_application_directory(letter, application.id)

send_email(settings.SENDGRID_SENDER, ['xxxxxx@gmail.com'], 'new application submitted',
           'new application submitted')

return Response(application.id, status=status.HTTP_200_OK)

现在发生的事情是,如果没有打开的应用程序,我会创建一个新的。 我想做的是添加另一张支票,即 Application.objects.filter(applicant=applicant_profile_id) 所以如果我有这个候选人的公开申请,它不会进入 application.save() 但它会发送一个错误。 我真的不知道该怎么做,这就是我需要你帮助的地方:)

先检查一下。这就是 queryset.exists() 的用途。

if Application.objects.filter(applicant=applicant_profile_id).exists() :
    # tell applicant he's being naughty

#carry on as in the code you posted