我有一个将对象分配给事件或自定义事件的视图。它首先尝试执行 Event,如果失败则应该执行 customEvent。我现在的代码是:
@login_required
def addEvent(request):
event_id = request.POST['event_id']
user = request.POST['profile']
user = Profile.objects.get(id = user)
try:
event = Event.objects.get(event_id = event_id)
user.eventList.add(event)
except event.DoesNotExist:
event = customEvent.objects.get(event_id = event_id)
user.customEventList.add(event)
return HttpResponse(status = 200)
但是,我被告知在“例外”行中分配之前引用了局部变量“事件”。嗯,这不就是DoesNotExist 的重点吗?不能分配吗?任何人都知道我将如何解决这个问题?