I have two tables in a database (that I’ve created): Entry and Nation. Every time a new entry is created, the user has to fill in what Nation it relates to. So an entry has two fields: Content [a charfield] and Nation [a foreign key to a Nation]. The thing is, on the homepage of the site, the most popular nations are displayed in order of how many entries they have. It seems inefficient to constantly look up how many foreign keys in the Entry table relate to each Nation, so I’m wondering how I can keep a counter. By this I mean, if I create an extra integer field for the Nations, how could I make it so that every time an entry is created, it increments the correct nation by 1, and every time an entry is destroyed, it decreases the correct nation by 1.
I have two tables in a database (that I’ve created): Entry and Nation .
Share
You could use the
post_savesignal, which is sent at the end of thesave()method.First, add (as you said) a
counter = IntegerField(default=0)to yourNationmodel.Then, everytime a new
Entryis created, increase that counter.Then, you could sort your
Nations with a simple query: