def prioritize():
 while True:
  hp_qs = Message.objects.high_priority().using(u'default')
  mp_qs = Message.objects.medium_priority().using(u'default')
  lp_qs = Message.objects.low_priority().using(u'default')
  while (hp_qs.count() or mp_qs.count()):
   while hp_qs.count():
    for message in hp_qs.order_by(u'when_added'):
     (yield message)
   while ((hp_qs.count() == 0) and mp_qs.count()):
    (yield mp_qs.order_by(u'when_added')[0])
  while ((hp_qs.count() == 0) and (mp_qs.count() == 0) and lp_qs.count()):
   (yield lp_qs.order_by(u'when_added')[0])
  if (Message.objects.non_deferred().using(u'default').count() == 0):
   break

def prioritize ( ) : while True : hp_qs = Message . objects . high_priority ( ) . using ( u'default' ) mp_qs = Message . objects . medium_priority ( ) . using ( u'default' ) lp_qs = Message . objects . low_priority ( ) . using ( u'default' ) while ( hp_qs . count ( ) or mp_qs . count ( ) ) : while hp_qs . count ( ) : for message in hp_qs . order_by ( u'when_added' ) : ( yield message ) while ( ( hp_qs . count ( ) == 0 ) and mp_qs . count ( ) ) : ( yield mp_qs . order_by ( u'when_added' ) [ 0 ] ) while ( ( hp_qs . count ( ) == 0 ) and ( mp_qs . count ( ) == 0 ) and lp_qs . count ( ) ) : ( yield lp_qs . order_by ( u'when_added' ) [ 0 ] ) if ( Message . objects . non_deferred ( ) . using ( u'default' ) . count ( ) == 0 ) : break
yield the messages in the queue in the order they should be sent .