Statistics logging for Django - part 2
In part 1 I explained how to build middleware and an associated model to capture page accesses, and tie them to a user session. Now that we have all this useful info logged we need to do something with it, like, display it. Unfortunately Django doesn't have a facility for using GROUP BY with mysql, so you have two major choices (there are more but we can ignore them): implement a custom request in a custom Manager (see snippet and snippet, or tagged snippets), or exploit a mysql view and model it in Django. Now for me I prefer the latter because it means my custom sql becomes a mysql customisation and as far as Django is concerned it is dealing with a normal table (but don't tell Django that it is read only), and thus the model code works, so subsequent queries and manipulations can exploit the ORM easily. My subjective and non-scientific experience is that using views is a lot more efficient/quick than using custom queries in the manager (it probably has to do with whatever optimisations exist with views, and the fact that you only fetch items when Django decides you need to fetch a row). So, how the hell do we do it?
First I created a model that describes what information I want to deal with (something which maps neatly on to our other model):
class UserActivity(models.Model):
session = models.OneToOneField(Session,
db_index=True,
null=True,blank=True,
primary_key=True)
user = models.ForeignKey(User,null=True,blank=True)
date = models.DateTimeField(
help_text="Date Request started processing",
auto_now_add=True,
db_index=True)
processing_time = models.IntegerField(
help_text="Total time spent on this user")
requests = models.IntegerField(
help_text="Total Requests in this session")
stats = UserActivityManager()
def __str__(self):
return '%s: %s %s - %s - %s' % (self.user,self.session,self.date,self.processing_time,self.requests)
class Admin:
list_display= ('user','session','date','processing_time','requests')The nice thing about this set up is when we aggregate our activity logs we can pull out random stuff like total processing time for requests for a user/session, along with number of requests/user/session (and thus average request time)
But that is just our model, we still need the magic. To implement the magic nicely I put some custom initial SQL into the sql directory of my application (in my case the housing application for this is called accounts, so I make a file called accounts/sql/useractivity.sql), you can read more about initial data here, Django fixtures).My SQL looks like this:
DROP TABLE accounts_useractivity;
CREATE OR REPLACE VIEW accounts_useractivity AS
SELECT i.session_id,
i.user_id,
MAX(i.date) as date,
sum(i.request_time) AS processing_time,
count(*) AS requests
FROM accounts_activitylog i
GROUP BY 1
ORDER BY NULL;
So first I tell mysql to drop the table that django just created (accounts_useractivity), and create a view in it's place. The view is very simple, in that it just GROUP BY the session_id. The real hair puller for me was figuring out that I needed to use the MAX(i.date) (see more about aggregate functions) to get the most recent access to float to the top when it normalises the data (otherwise the GROUP BY normally ORDER BY the session_id, which helps no one), the ORDER BY NULL is an optimisation to tell GROUP BY not to ORDER BY. I am hoping that because date is an INDEX (from our logging model) it shouldn't cost too much to do a MAX. (I would like someone with Much MYSQL-fu to point out any further optimisations to this, or even alternative approaches to the whole thing).
So now we have an aggregating VIEW which Django maps using it's ORM, so that to figure out sessions which have been active in the last x minutes (where x is a datetime.timedelta object) we simply do a:
UserActivity.objects.get_query_set().filter(date__gte=datetime.now()-x)I wrote a custom manager for getting recent sessions etc., but that is an exercise for the reader. What I did include in my model is something which returns a stepped "request_weight" i.e. session requests / largest session request x steps, which in my case defaults to 6. This means I can style my users like one would a "tag cloud", so very active sessions will grow bigger than less active sessions. I needed to implement a helper function in the custom manager to return the session with the most requests.
The final tip is to use a context processor to make the information available to all your templates, although you could do it with middleware (maybe middleware is the proper way to do it?).

















'request.session' is no longer a Session object, it's a SessionStore object that is different based on whether you use DB, file or cache sessions. I switched the 'session' part of the model to just be a charfield that is populated with the session id. I really only cared about which 'activity's were grouped as part of a session.
Essay AND Custom Research Paper AND Term Papers
Your article is great and there is no solution to this issue most of the companies are making money and wiping of their people. Its funny to real the article relation with real estate lolzzz. I have been looking for rent Apartment in Dubai since I move to Dubai . Properties for rent in dubai are expensive for me but one of my friend wants to Sell villa in Arabian ranches which might be a better option in this down market what do you think guys ?
Great post!
Djongo made the process of creating middleware very easy and now I can easily create addresses for datacall. Discount Sunglasses
You will surprise to find the high quality tiffany jewelry in much.Everyone will focus on the shinning of
tiffany co jewelry without awareness of
rovide 100% sterling silver Tiffany jewelry,you can buy discount Tiffany & Co jewelry here.Tiffany And Co Jewelry is the best jewellry.
discount tiffany jewelry, Tiffany Jewelry, Tiffany Jewellery, Tiffany Silver, Tiffany, Tiffanys, Tiffany's Jewelry.We Provide a wide range of fashionable
tiffany co jewelry, including
Links London
In 1950 Tiffany's had its biggest boost in popularity as Truman Capote's Breakfast at Tiffany's was published. Tiffany's was shot to worldwide fame in 1961 when the film adaptation staring Audrey Hepburn was released. This film and its star became icons, as did Tiffany's
Tiffany Bracelets
Tiffany Rings
cheap tiffany with.Discounted Tiffany & Co silver jewelries are provided in our Tiffany’s online outlet store
Links Of London
Thanks for sharing.
thanks for sharing
Titan Bet Gratta e Vinci Titan Bet Bingo Online
Some great info on here, why did i not find this site sooner! Many thanks and keep posting. how to get 6 pack abs | how to get six pack abs | how to get a 6 pack quick | how to get 6 pack abs fast
Thank you for sharing beautiful articles. I will recommend my friends to follow this website.
free music download sites
Agree with you,it's awesome.
health questions answered | free recipes online | food health questions | All QA | Small toaster ovens
It is my great pleasure to visit your website and to enjoy your excellent post here. I like that very much. I can feel that you paid much attention for those articles, as all of them make sense and are very useful. Thank you for sharing with us static caravan insurance
Great Articles………….. thank you
Generic Viagra | Cheap Generic Viagra | Generic Levitra | Generic Viagra | Cheap Generic Viagra | Kamagra | Cheap Generic Viagra | Finpecia | Penegra | Generic Viagra and Kamagra | Generic Viagra
viagra Senza Ricetta
lioresal Rezeptfrei
albenza Senza Ricetta
Acheter du albenza en France
Comprar cytotec Farmacia
Prix du vermox en Pharmacie
cialis Senza Prescrizione Medica
kamagra Senza Prescrizione
effexor xr Rezeptfrei Bestellen
Ou Acheter minocin en ligne
Comprar strattera Farmacia
nolvadex Rezeptfrei
Comprare cytotec Italia
clomid Senza Ricetta in Svizzera
effexor xr Senza Prescrizione
minocin Senza Prescrizione Medica
minocin Senza Ricetta
kamagra Rezeptfrei
effexor xr Rezeptfrei Bestellen
lioresal Rezeptfrei Apotheke
cialis super active plus Rezeptfrei Bestellen
cytotec Ohne Rezept
flagyl Rezeptfrei
propecia Rezeptfrei Apotheke
lamisil Rezeptfrei Kaufen
cytotec Senza Prescrizione Medica
cipro Rezeptfrei
Ohne Rezept silagra Apotheke
Vendita flagyl in Italia
flagyl Senza Ricetta in Svizzera
silagra Comprar
Achat levitra en ligne
Ohne Rezept kamagra Apotheke
inderal Rezeptfrei
Achat clomid en ligne
minocin Comprar
silagra Senza Ricetta in Svizzera
wow,my blog:health question health blog
medical health blog health blogspot
A free sex video of sweet natural hairy Swamy Nithyananda’ having sex with a top tamil actress and other nude girls was broadcast on TV live and has shocked people across India. Naked girls were typed on video by anonumous author. Since a Swamy is supposed to be a spiritual person- this revelation has followers questioning hairy bush Nithyananda's faith. Originally this xxx video was posted on youtube but then moved to other sex tube portals.
ABB728019384 порно видео
Great post dude, your blog rocks!
auberge de jeunesse berlin
You are cute =)
breast uplift surgery pilates exercise program honeymoon getaways
Achat effexor xr Pas Cher
Prix kamagra France
Comprare effexor xr Online in Italia
kamagra Comprar Espana
Ou Acheter kamagra en ligne
Acheter kamagra oral jelly Moins Cher
lipitor Sans Ordonnance Belgique
Comprar clomid Contrareembolso
Ou Acheter lipitor en ligne
Achat levitra Sur Internet
Comprar strattera Sin Receta
anafranil Vendita Senza Ricetta
Prezzo lasix in Farmacia
proscar Comprar Sin Receta
Prix strattera Pharmacie
Prezzo vermox Italia
cytotec Prix Officiel
augmentin Senza Ricetta in Svizzera
cytotec Pas Chere
Comprar proscar Farmacia
lasix Sin Receta en Farmacia
accutane Senza Ricetta Medica
accutane Comprar Espana
Acheter anafranil France
cialis Donde Comprar
levitra Prezzo Farmacia
kamagra Vendita Senza Ricetta
lasix Comprar Sin Receta
lipitor Senza Prescrizione
vermox Online Italia
viagra Prix Officiel
Comprar effexor xr Internet
nolvadex Sin Receta
Comprar lasix Farmacia
Acheter levitra France
inderal Prix en France
lamisil Senza Ricetta
Comprar kamagra oral jelly Farmacia
Acheter vermox
minocin Comprar Online
Acheter anafranil
Precio anafranil Espana
Precio proscar Con Receta
viagra Online Italia
Achat imitrex Sans Ordonnance
Inderal
Achat Albendazole en France
Prix du Lipitor en Pharmacie
Xenical Senza Ricetta in Italia
Mega Hoodia Prezzo Farmacia
Ou Acheter Valtrex en ligne
Levitra
Viagra Oral Jelly
Mega Hoodia
Comprar Mega Hoodia Online
Zocor Online Sicuro
Precio Levitra Espana
Nexium Prezzo Farmacia
Amoxil Online Contrareembolso
Achat Ketoconazole Sur Internet
Flagyl Comprar Online
Prix Hoodia France
Viagra Comprar Online
Vaniqa Pas Chere
Vendita Levitra Senza Ricetta
Achat de Viagra Oral Jelly en Pharmacie
Acheter Levitra Moins Cher
Vendita Ampicillin Online
Xenical Preis Apotheke
Comprare Mega Hoodia Italia
Viagra Super Active Moins Cher en Pharmacie
Cloud Nine Hoodia Moins Cher en Pharmacie
Cipro Prix Pharmacie
Comprare Levitra Online
Comprar Inderal Online
Acheter Prilosec Moins Cher
Viagra Oral Jelly Kaufen
Inderal Sans Ordonnances
Amoxil Wirkung
Prevacid Vendita Libera
Achat Bactrim France
Valtrex Kaufen
Ketoconazole Pas Chere
Prix Norvasc Pharmacie
Precio Cialis Soft Tabs Con Receta
Viagra Super Active Comprar
Levitra
Comprare Viagra Italia
Zantac Ohne Rezept Bestellen
Propecia Pas Chere
Viagra Soft Tabs Precio Farmacia
Bestellen Prevacid
Valtrex Online Kaufen
Thanks for sharing your views on the topic. It makes one think and look the other side of the story.
hosting
web hosting service
domain hosting
unlimited hosting
cheap web hosting
Comparability and replica Longines watches distinction essay is Replica A.Lange Sohne without fake handbags doubt one of fake Jaeger Le Coultre Watches the replica Breitling watches commonest assignments in American replica Rado watches excessive colleges and Replica TAG Heuer Watches universities. designer handbags In the sort fake Balenciaga handbags of replica watches an essay the Replica Versace scholars have to compare two (in some essays replica Jaeger LeCoultre watches a number of) issues, problems, occasions or ideas- replica watches replica tag heuer and consider their resemblances and differences. This type of an essay advances and develops your crucial replica Piaget watches considering in addition to an essay your argumentation and understanding of the importance of the Replica IWC Watches occasions fake Marni handbags and issues that you simply compare.
There s an instance of Replica Loewe the headings of among the compare/contrast assignments.
Compare and fake TAG Heuer Watches contrast the weather situations for the growing of the cotton between Texas and California.
Examine fake watches the strategy to the Soviet Union of F.D. Roosevelt and H. Truman. Replica Tissot What are the cheap clothing similarities/the variations of their Replica Cartier coverage?
Compare and the essays contrast the flicks God Replica Thomas Wylde handbags Farther replica louis vuitton and Once fake A. Lange and Sohne Watches upon a time inAmerica. />
Generally, fake chanel chances replica watches are you ll be asked to check, replica Jaeger Le Coultre sometimes you may be replica IWC watches requested to contrast, and on a number of events Replica Omega each actions mentioned ought to be performed.
But, on the similar fake Jaeger Le Coultre Watches time comparison/contrast might replica IWC watches be a part of nike shoes some essay as w
great site increase semen volume
Why choose Volume Pills
What can VolumePills do for me
How VolumePills works
Volume Pills, no question too difficult
Hormones, the environment and your sex drive
VolumePills and your lifestyle – how to get that maximum effect
Low testosterone levels or testosterone deficiency
Sperm Increase
Increase Semen Production
What are Drlizen™ and Solidilin™
Does Weight Affect Sperm Quality
How to Increase Your Sperm Production through Volume pills
Legends behind semen
How to get boost in bedroom
Volume Pills
Diet and semen production – VolumePills
What is semen made of
What Environmental Factors Can Affect Impotence
Ingredients of VolumePills and their explanations
Get Ready for Longer Lasting Erections and Bigger, Better Orgasms
Review of Volume Pills
Bigger Loads and Stronger Orgasms with the Help of a Tiny Pill.
How do Volume Pills Actually Work
Enjoy Sexual Control and Kiss Premature Ejaculation Goodbye
Nourish your Male Reproductive System with Volume Pills
Everything you Need to Increase, Size, Frequency, and Quality of your Ejaculations, Erections, and Orgasms
Volume Pills Produced from 100% Natural Formulation
Do women like a lot of cum
How VolumePills increase sperm count
How VolumePills help erection hardness
Reasons for the Increase or Decrease of Sperm Production
Threats to Male Fertility
Male Infertility
Your Semen and You
The Sperm Cell: An Overview
Worried about infertility? Try Zinc.
Loved to read your blog. I would like to suggest you that traffic show most people read blogs on Mondays. So it should encourage blogger to write new write ups over the weekend primarily.
detox tea recipe cheap liability insurance makeup for aging skin acne laser surgery jewish speed thread post heritage wsum
asian fashion
I will aslo try this code into my site. halloween contacts
So good borse replica
There's something wrong with the display, it doesn't seem to display all the comments as they get further to the right. Can you fix that?
nikon s570 | lime green bedding
I would like to test this code in my site multiple poker tables
great post.
SEO
Seo marketing
Search engine marketing
web design
web development
Thanks for this code. I appreciate that you have publish this information. It could be useful in my websites. Thanks again.
Thomas - Essay Writing
I will contact you via email so that you can clear some of these things up for me. Again, very well written article. Keep up the good work.How to get pregnant
P90X
Acai Berry
thanks for this. nice blog.
Online Business
Blogging Business Internet Marketing Healthy Lifestyle Online Games Travel Insurance Weight Loss Women Smart Business Finance Insurance Info Tech Gadget Home Improvement Latest technology Gadget Blackjack Casinos Home Real Estate Credit Finance Food Restaurant Grill GPS Techno Gadget News Shopping Center Credit Card Consolidation tax accounting Pets Dog Shop Majalah Koperasi
Your article is great and there is no solution to this issue most of the companies are making money and wiping of their people. Thanks for sharing.
Regards,
michigan auto insurance
chanel handbags
gucci handbags
hermes handbags
louis vuitton handbags
designer handbags
designer handbags
vertu phones
designer handbags reviews
replica handbags
replica phones
vertu replica
tag heuer phone
mobiado
cartier-phones
goldvish
rolex mobile
porsche phone
replica blackberry
iphone replica
The subjective and non-scientific experience is that using views is a lot more efficient/quick than using custom queries in the manager. Thanks.
Regards
auto insurance quotes
Pretty good post. I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog posts. Any way I'll be subscribing to your feed and I hope you post again soon. Thanks.
Regards
leasehold acquisition information
Its really an active session. I needed to implement a helper function in the custom manager to return the session with the most requests. Thanks for sharing.
Regards,
income tax information
nice service.
SEO
Thanks a lot for enjoying this beauty article with me. I am appreciating it very much! Looking forward to another great article. Good luck to the author! all the best! daily detox tea anti aging makeup acne removal surgery cheap contractor liability insurance jewish speed post thread heritage philanthropy
Pretty good post. I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog posts. Any way I'll be subscribing to your feed and I hope you post again soon.
male enhancement
spread betting
I tell mysql to drop the table that django just created (accounts_useractivity), and create a view in it's place. The view is very simple, in that it just GROUP BY the session.internet marketing search engine
Oh, My god, Beijing let me think what happy the emperor is!! My dream is becoming an Emperor.Insurance
GadgetNewsToday.com provide the latest gadget news and review from all over the world.
TravelOfChoice.com provide online travel information for world destinations. Travel Guide .
Looking for health tips and tips?
CarFinanceDaily.com provide car finance tips, car financing information to help you understanding credit scores and financing decisions
The latest technology news, science news, tech and science breakthroughs, and future tech. Tech and Science News .
Have questions about auto insurance news? AutoInsuranceDaily.org is the right place for you.
Why reply?
Lebensversicherung verkaufen
Ankauf Lebensversicherung
Verkauf Lebensversicherung
Lebensversicherung verkaufen
Personal blogs are replica Ulysse Nardin watches only one type of replica Cartier blog. Blogging is Replica Chanel Watches not considered replica Rolex as an effective way fake chanel to market products Replica A.Lange Sohne by replica Zenith many marketers because Replica Versace handbags usually when you think of Replica Versace a blog you think of an online diary or a replica Chanel watches site that is dedicated to someone trying to replica louis vuitton replica handbags get exposure in one aaa handbags form or another.
When you read the word blogging what do you replica Longines watches think of? Some people have images of a teenager blogging about random school yard gossip. Do you think of Replica Bally handbags someone like Heather nike shoes Armstrong who earns enough money fake Jaeger Le Coultre Watches through replica Cartier watches blog advertising to support Replica Giverchy her familyeven though her fake Marni handbags main blogging topic is herself Replica Ulysse Nardin Watches and her kids? Do you think about some random guy with no life who spends all day blogging replica handbags about a computer game hes addicted to? Did you know that blogging can fake TAG Heuer Watches help build your internet marketing business? Have you Replica IWC ever considered replica Panerai watches that blogging could be a great way to bring replica Zenith in revenue? Replica Cartier There fake Balenciaga handbags are plenty of logical fake Jaeger Le Coultre Watches reasons replica Rolex watches why replica Omega watches blogging can help any internet marketer to succeed. replica watches news Below are just some replica omega reasons why blogging can be an advantage.
Blogging is fake Cartier Watches a spectacular experience! Blogging is the only type of website that enables Replica Audemars Piguet Watches you to share information designer handbags with readers in the way that it does; th
I needed to implement a helper function in the custom manager to return the session..cheap hosting
The other day my friends recommed me few fashion onlinecoach handbags outlet containslouboutin shoes ,gucci handbags ,chanel handbags ,miu miu handbags ,Balenciaga Handbags ,Louis Vuitton Wallets , christian louboutin , Summer comes and I want to buy one pair ofchristian louboutins ,Because I found there are so manychristian louboutin sale online with low prices. I decided also buy the discount christian louboutin ,cl shoes ,black christian louboutin ,buy christian louboutin , red sole shoes , christian louboutin boots , christian louboutin pumps , christian louboutin sandals ,mbt shoes ,mbt sport shoes ,discount gucci handbags ,gucci purses ,discount coach handbags together. When few of our friends go shopping last week, I saw one shop offercheap jordan shoes likeair jordan shoes sale ,air jordan 1 shoes ,cheap air jordan ,new air jordans ,nike jordan shoes ,Air Jordan 3 ,Air Jordan 4 ,Air Jordan 7 ,Air Jordan 8 ,Air Jordan 9 ,Air Jordan 10 ,Air Jordan 12 ,Air Jordan 13 ,Air Jordan 14 ,Air Jordan 15 ,Air Jordan 16 ,Air Jordan 17 ,Air Jordan 18 ,Air Jordan 19 ,Air Jordan 20 ,Air Jordan 21 ,Air Jordan 22 ,Air Jordan 23 ,Air Jordan 2010 ,kids jordan ,jordan low ,sneakers jordan ,retro jordan shoes ,jordan for sale ,jordan 6 retro ,kids jordans ,jordans size ,jordan shoes shoes ,authentic jordan ,grey jordan p90x workout ,px90 , p90x nutrition ,p90x fitness ,p90x extreme ,p90x reviews ,p90x schedule ugg australia , ugg classic tall , ugg classic short , ugg australia boots , ugg tall boots , ugg short boots , ugg sale , ugg slippers , ugg classic tall boots , classic short ugg boots ,ugg boots sale ,cheap ugg boots ,ugg on sale ,classic tall uggs ,classic short uggs ,ugg classic mini ,ugg boot sale ,uggs classic tall boots ,ugg boots for sale ,ugg kids sale ,uggs womens classic tall
Amazing post, thanks to you for the article. I appreciate your work, the post is extremely helpful. Thanks for sharing.
I come across a blog that's both informative and entertaining, and let me tell you, you've hit the nail on the head. Your blog is important; the issue is something that not enough people assignment writing assignment help
are talking intelligently about.
Post new comment