有没有一种方法可以处理来自不同模型的两种异常,并且仍然不将其单独作为上下文传递。
Views.py
class ProfilePage(DetailView):
model = models.UserCreation
context_object_name = 'profile'
def get_context_data(self, *args, **kwargs):
context = super(ProfilePage, self).get_context_data(*args, **kwargs)
user = User.objects.get(username=UserCreation.objects.get(id=self.kwargs.get('pk')))
print(self.request.user,user,self.kwargs.get('pk'))
try:
context['data'] = ProfileData.objects.get( user=user)
context['userdata'] = User.objects.get( username=user)
context['creationdata'] = UserCreation.objects.get(user=user)
context['friends'] = Friends.objects.get( user=self.request.user,added=user)
context['sorted'] = sorted(chain(AddStatus.objects.filter(user=user), ImageLib.objects.filter(user=user)),
key=lambda instance: instance.date, reverse=True)
except ((ProfileData.DoesNotExist as e) or (Friends.DoesNotExistas as f)) :
if e:
context['data']= None
elif f:
context['friends'] = None
return context
答案 0 :(得分:1)
是的,您应该使用两个try
-except
范围。实际上,最好不要写长try
-except
范围,因为那样就不知道是什么触发异常了。因此您可以像这样实现:
try:
context['data'] = ProfileData.objects.get( user=user)
except ProfileData.DoesNotExist:
context['data']= None
context['userdata'] = User.objects.get( username=user)
context['creationdata'] = UserCreation.objects.get( user=user)
try:
context['friends'] = Friends.objects.get( user=self.request.user,added=user)
except Friends.DoesNotExist:
context['friends'] = None
context['sorted'] = sorted(
chain(AddStatus.objects.filter(user=user),
ImageLib.objects.filter(user=user)),
key=lambda instance: instance.date, reverse=True
)
如果有多个 ProfileData
个问题,则可以使用.first()
来代替,如果有,则返回None
没有要返回的行:
context['data'] = ProfileData.objects.filter(user=user).first()
context['userdata'] = User.objects.get(username=user)
context['creationdata'] = UserCreation.objects.get(user=user)
context['friends'] = Friends.objects.filter( user=self.request.user,added=user).first()
context['sorted'] = sorted(
chain(AddStatus.objects.filter(user=user),
ImageLib.objects.filter(user=user)),
key=lambda instance: instance.date, reverse=True
)