algorithm - Filter items with Django Query -


i'm encountering problem , seek help.

the context: i'm having bag of balls, each of has age (red , blue) , color attributes.

what want top 10 "youngest" balls , there @ 3 blue balls (this means if there more 3 blue balls in list of 10 youngest balls, replace "redudant" oldest blue balls youngest red balls)

to top 10:

sel_balls = ball.objects.all().sort('age')[:10] 

now, satisfy conditions "at 3 blue balls", need process further:

  1. iterate through sel_balls , count number of blue balls (= b)
  2. if b <= 3: nothing
  3. else: additional b - 3 red balls replace oldest (b - 3) blue balls (and these red balls must not have appeared in original 10 balls taken out). figure can getting oldest age value among list of red balls , query like:

    add_reds = ball.objects.filter(age >= oldest_sel_age)[: b - 3]

my question is:

  1. is there way can satisfy constraints in 1 query?
  2. if have 2 queries, there faster ways 1 method mentioned above?

thanks all.

use q complex queries database: https://docs.djangoproject.com/en/dev/topics/db/queries/#complex-lookups-with-q-objects


Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -