0


I know in general it's good practice to rely on your database for actions like getting sum of records. However here's a special situation:
I'm using raw sql with django and I want to get a list of records first, let's say I want a list of books and their prices and their discount percents, after that I want to have the sum of prices and the sum discount (price * discount price for each book). for example :

one way to do this is to use the SUM() function of SQL but since I already have the records why not just use a for loop to calculate that? I know database is supposed to be faster but it takes some time for Django to connect to the database and the number of books are not that much (around 5).
can someone help me, which solution is better?
any help appreciated and thanks in advance.

Bahman Rouhani
  • 1,139
  • 2
  • 14
  • 33
  • 1
    I think this link might be helpful for you: [use arithmetic functions with Django query ](https://stackoverflow.com/questions/45593440/how-to-execute-arithmetic-operations-between-model-fields-in-django?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa) – Syed Mohammad Hosseini Apr 08 '18 at 06:53
  • 1
    I don't think both have a large amount of performance difference in your context (appx. 5 records). But, if you have a large amount of data, go for `SQL Aggregate functions`. – JPG Apr 08 '18 at 06:57

1 Answers1

1

You seem to be talking about making a separate database call to do the aggregation. Your intuition is right that the overhead of making that call would far outweigh any other performance differences.

But you don't need to make a separate call; you can do the aggregation in the same call that fetches the complete records. However, there's little point in doing that if you can just do the aggregation yourself in Python. It's possible that for large amounts of data there could be a performance advantage to letting the database do it, but on the other hand the database is more likely to be a performance bottleneck than your application server.

With five rows performance won't be a factor either way. I would personally prefer to do it Python, since it's a more powerful and flexible language than SQL, but it doesn't really matter.

Kevin Christopher Henry
  • 46,175
  • 7
  • 116
  • 102