Issue
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 object is empty. I would appreciate it if you share your solution.
Thanks
Solution
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)]
Answered By - dani herrera
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.