Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to denormalize data in Django? [closed]

I'm developing a simple web app, and it makes a lot of sense to store some denormalized data.

Imagine a blogging platform that keeps track of Comments, and the BlogEntry model has a "CommentCount" field that I'd like to keep up to date.

One way of doing this would be to use Django signals.

Another way of doing this would be to put hooks directly in my code that creates and destrys Comment objects to synchronously call some methods on BlogEntry to increment/decrement the comment count.

I suppose there are other pythonic ways of accomplishing this with decorators or some other voodoo.

What is the standard Design Pattern for denormalizing in Django? In practice, do you also have to write consistency checkers and data fixers in case of errors?

like image 415
slacy Avatar asked Jul 08 '09 22:07

slacy


2 Answers

You have managers in Django.

Use a customized manager to do creates and maintain the FK relationships.

The manager can update the counts as the sets of children are updated.

If you don't want to make customized managers, just extend the save method. Everything you want to do for denormalizing counts and sums can be done in save.

You don't need signals. Just extend save.

like image 168
S.Lott Avatar answered Nov 15 '22 18:11

S.Lott


I found django-denorm to be useful. It uses database-level triggers instead of signals, but as far as I know, there is also branch based on different approach.

like image 10
gorsky Avatar answered Nov 15 '22 16:11

gorsky