Reputation: 2378
I am initializing variables to None
as default value. If the queryset returns no objects then the program will not fail.
Is there a shorter method on this? Thanks
qs_data = {
'flal_id_no' : None,
'mail_id_no' : None,
'subject_id_no':None,
'pdsbj_id_no':None,
}
qs = vFileAllocation.objects.values().filter(track_id_no=get_track_id_no)[0]
if qs:
qs_data['flal_id_no'] = qs['flal_id_no']
qs_data['mail_id_no'] = qs['mlal_id_no']
qs_data['subject_id_no'] = qs['subject_id_no']
qs_data['pdsbj_id_no'] = qs['pdsbj_id_no']
Upvotes: 0
Views: 196
Reputation: 4404
Basic python or operator (return default if None) can be used:
queryset[0]
- gets first object from the queryset result, so in case no matches found - queryset will contain no elements (queryset == <QuerySet[]>
) and getting first element from it [0]
will fail.
Correct way is to use .first()
on queryset to evaluate it and get first result or None
.
For this example this can be done as a one-liner:
qs_data = vFileAllocation.objects.values() \
.filter(track_id_no=get_track_id_no) \
.first() or qs_data
or
qs = vFileAllocation.objects.values() \
.filter(track_id_no=get_track_id_no).first()
# qs is already evaluated
qs_data = qs or qs_data
Upvotes: 1