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:
- iterate through sel_balls , count number of blue balls (= b)
- if b <= 3: nothing
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:
- is there way can satisfy constraints in 1 query?
- 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
Post a Comment