def add_new_user_history(user_profile, streams):
 one_week_ago = (now() - datetime.timedelta(weeks=1))
 recipients = Recipient.objects.filter(type=Recipient.STREAM, type_id__in=[stream.id for stream in streams if (not stream.invite_only)])
 recent_messages = Message.objects.filter(recipient_id__in=recipients, pub_date__gt=one_week_ago).order_by('-id')
 message_ids_to_use = list(reversed(recent_messages.values_list('id', flat=True)[0:100]))
 if (len(message_ids_to_use) == 0):
  return
 already_ids = set(UserMessage.objects.filter(message_id__in=message_ids_to_use, user_profile=user_profile).values_list('message_id', flat=True))
 ums_to_create = [UserMessage(user_profile=user_profile, message_id=message_id, flags=UserMessage.flags.read) for message_id in message_ids_to_use if (message_id not in already_ids)]
 UserMessage.objects.bulk_create(ums_to_create)

def add_new_user_history ( user_profile , streams ) : one_week_ago = ( now ( ) - datetime . timedelta ( weeks = 1 ) ) recipients = Recipient . objects . filter ( type = Recipient . STREAM , type_id__in = [ stream . id for stream in streams if ( not stream . invite_only ) ] ) recent_messages = Message . objects . filter ( recipient_id__in = recipients , pub_date__gt = one_week_ago ) . order_by ( '-id' ) message_ids_to_use = list ( reversed ( recent_messages . values_list ( 'id' , flat = True ) [ 0 : 100 ] ) ) if ( len ( message_ids_to_use ) == 0 ) : return already_ids = set ( UserMessage . objects . filter ( message_id__in = message_ids_to_use , user_profile = user_profile ) . values_list ( 'message_id' , flat = True ) ) ums_to_create = [ UserMessage ( user_profile = user_profile , message_id = message_id , flags = UserMessage . flags . read ) for message_id in message_ids_to_use if ( message_id not in already_ids ) ] UserMessage . objects . bulk_create ( ums_to_create )
give you the last 100 messages on your public streams .