2

Which of these two strategies would be better for calculating upvotes/downvotes for a post:

These are model fields:

ups
downs
total

def save(self, *args, **kwargs): # Grab total value when needed
    self.total = self.ups - self.downs
    super.(yourmodel, self).save(*args, **kwargs)

Versus:

ups
downs

def total(ups, downs): # totals will just be computed when needed
    return ups - downs # versus saved as a column

Is there really any difference? Speed? Style?

Thanks

4

2 回答 2

4

I would do the latter. Generally, I wouldn't store any data that can be derived from other data in the database unless the calculation is time-consuming. In this case, it is a trivial calculation. The reason being that if you store derived data, you introduce the possibility for consistency errors.

Note that I would do the same with class instances. No need to store the total if you can make it a property. Less variables means less room for error.

于 2012-09-23T19:43:55.387 回答
1

I totally agree with @Caludiu. I would go with the second approach, but as always there are pros and cons:

The first approach seems harmless but it can give you some headaches in future. Think about your application evolution. What if you want to make some more calculous derived from values in your models? If you would want to be consistent, you will have to save them too in your database and then you will be saving a lot of "duplicated" information. The tables derived from your models won't be normalized and not only can grow unnecessarily but increase the posibility of consistency errors.

On the other hand, if you take the second approach, you won't have any problems about database design but you could fall into a lot of tough django queries because you need to do a lot of calculus to retrieve the information you want. These kind of calculus are riddiculy easy as an object method (or message, as you prefer) but when you want to do a query like this in django-style you will see how somethings get complicated.

Again, in my opinion, you should take the second approach. But it's on you to make the desicion you think fits better on your needs...

Hope it helps!

于 2012-09-23T19:56:10.137 回答