-1

Let's say I have a model like this:

+-----------+--------+--------------+
| Name      | Amount | Availability |
+-----------+--------+--------------+
| Milk      | 100    | True         |
+-----------+--------+--------------+
| Chocolate | 200    | False        |
+-----------+--------+--------------+
| Honey     | 450    | True         |
+-----------+--------+--------------+

Now in a second model I want to have a field (also named 'Amount') which is always equal to the sum of the amounts of the rows which have Availability = True. For example like this:

+-----------+-----------------------------------------------+
| Inventory | Amount                                        |
+-----------+-----------------------------------------------+
| Groceries | 550 #this is the field I want to be dependent |
+-----------+-----------------------------------------------+

Is that possible? Or is there a better way of doing this?

kristian
  • 730
  • 5
  • 16
  • your question is bit unclear to me. Do you want the 2nd model hold up the summed up of the 1st model's "Amount" data ? – kmonsoor Jan 15 '15 at 23:33
  • 1
    Why would you want that stored in a table column, instead of calculating it in the fly when necessary? – Daniel Roseman Jan 15 '15 at 23:35
  • I thought this would be simpler and faster, as the database gets bigger. There'll be many relations which need to be shown at the same time. I didn't want to cause an overload of queries. – kristian Jan 15 '15 at 23:41
  • `100+450 = 550`, not `600` –  Jan 15 '15 at 23:47

1 Answers1

0

Of course that is possible: i would recommend one of two things:

  1. Do this "on the fly" as one person commented. then store in django cache mechanisim so that it only calculates once in awhile (saving database/computation resources).

  2. create a database view that does the summation; again it will let the database cache the results/etc. to save resources.

That said, I only think #1 or 2 is needed on a very large record set on a very busy site.

warath-coder
  • 2,087
  • 1
  • 17
  • 21
  • I will do it "on the fly" as some of you suggested! Thanks! But what is a database view? – kristian Jan 16 '15 at 00:03
  • 2
    a database view is far beyond the scope of this question and the comment section :) http://stackoverflow.com/questions/1278521/why-do-you-create-a-view-in-a-database – warath-coder Jan 16 '15 at 00:04