python - Most efficient way to filter for lowest values in queryset -


given:

some_list = someclass.objects.filter(something=something).order_by('-x','-y') 

in english: some_list filtered list of someclass objects, ordered 2 values, first x, y.

if want limit number of entries in list value z, can this:

final_list = some_list[:z] 

but if want limit number of entries value, randomize "cut-off entries" before do? i'm having hard time describing, example:

sc  x  y   2  3  b  1  2  c  1  1  d  1  1  e  1  1  f  1  0  g  0  3 

if z=3 then, using method, final_list = (a,b,c). want final_list include , b because above others(a has greater x others, , b tied second x has greater y), seeing cut-off @ c x=1,y=1, , there 2 other objects "tied" c, third slot c, d, or e.

i pull some_list apart hand , examine values , start putting them final_list until hit z, hoping there better way don't know of. in, less lines of code, less processing power, etc.

so example, expect 1 of these outputs, @ random:

final_list = (a, b, c) final_list = (a, b, d) final_list = (a, b, e) 

if z = 4, expect 1 of these outputs:

final_list = (a, b, c, d) final_list = (a, b, c, e) final_list = (a, b, d, c) final_list = (a, b, d, e) final_list = (a, b, e, c) final_list = (a, b, e, d) 

hopefully clear.

you simplistic like, annotating query average values of x , y, , then, picking values above average. example, like:

some_list = someclass.objects.filter(                 something=something             ).annotate(                 average_x=avg("x"), average_y=avg("y")             ).order_by(                 '-x','-y'             )  def passes_threshold(x, y, avgx, avgy):     '''simplistic function check if combination of x & y better     another. update better suit context.     '''     return (x + y) > (avgx + avgy)  # use filter instead, if want values list matching, # if want until first few match, required_list = itertools.takewhile(passes_threshold, some_list) 

Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

ios - Change Storyboard View using Seague -