Django query optimization: retrieve values in groups possible?
I have:
active = Node.objects.filter(status = 'a')
potential = Node.objects.filter(status = 'p')
hotspot = Node.objects.filter(status = 'h')
I'm wondering: is it's possible to do it in a better way?
EDIT: maybe i didn't explain myself very well. I need to have 3 lists with the 3 different status. If I do just 1 query then I will have to loop over the list to make 3 new lists, but if the list if very lo开发者_如何学编程ng wouldn't that be inefficient?
Even better, use in
:
Node.objects.filter(status__in=['a', 'p', 'h'])
Edit after comment Don't know why that would be inefficient. Perhaps one improvement would be to add .order_by('status')
so you get an ordered queryset, then split when you iterate through. Likely to be a micro-optimization though.
Take a look at Django Q objects
from django.db.models import Q;
Node.objects.filter(Q(status = 'a') | Q(status = 'p' | Q(status = 'h'))
Source: https://docs.djangoproject.com/en/dev/topics/db/queries/#complex-lookups-with-q-objects
精彩评论