I think there should be an easier and more elegant solution but I cannot find it. I have the following in views.py. As you can see I achieve want I want with numpy but I want a direct solution:
myarray = np.asarray(MyDatabase.objects.filter(
status='user').values_list('name','age').order_by('age'))
if myarray.size==0:
myarray=np.zeros((1,2))
What I want is to set zeros when the object queryset is empty, e.g., in this case status=user is filtered from my Database Table and let's assume that no status=user exists, then I want 'name' and 'age' to show 0 as outputs. I did it but I just dislike using the extra lines. I wonder if there is a way to directly ouput zeros when the objects filter is empty. In the documentation it says that django 4.0 comes with default() option in the queryset to do precisely what I'm asking but no example is given. I would appreciate it if you share your solution
Thanks
CodePudding user response:
Self explained:
# db values
query = (
MyDatabase
.objects
.filter(status='user')
.values_list('name','age')
.order_by('age')
)
# set db values or zeros if no values
myarray = query or [(0, 0)]
