Statistics logging for Django - part 2

brad's picture

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?).

Trackback URL for this post:

http://whijo.net/trackback/110

'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.

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

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

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

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

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

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

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

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

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.

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

The content of this field is kept private and will not be shown publicly.
Captcha
This question is used to make sure you are a human visitor and to prevent spam submissions.
Syndicate content

Recent comments

About this website

Whijo.net is the online internets of Bradley Whittington, Amanda Joseph, and our son Finley James Whittington. "Whijo" is 29% Whittington, 33% Joseph, and 37% Internet. Quite Web 2.0 of us.