Title: What is the most efficient way to count votes on an object?
Tags: python;mysql;django;oop;entity-relationship
Question: I want to count votes on model object.  I am thinking there are two ways to accomplish this:
Approach 1
class Question(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
vote_count = models.IntegerField()
And then get the model, update the count, then re-save the model.
Approach 2
class Vote(models.Model):
user = models.ForeignKey(User,on_delete=models.CASCADE)
class Question(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
votes = models.ManyToManyField(Vote,related_name='questions')
In this way I can add to the votes and then count on all votes when I need a summary.
I want to do things like sort by most votes and other summation operations.
Which approach is most efficient from a database cost perspective as well as future scalability?


Here is another answer: First of all, the two approaches you've listed are not exactly equivalent - in the first you're only persisting the information about the total number of votes, whereas in the second one you also keep the information about the user who voted (and you might want to add additional relevant fields).
Obviously, the first approach is more efficient since it won't require a join like the second one, but I'll be a bit careless here and say that you probably don't have to worry about that - don't forget what Mr. Knuth said which might be relevant here:
We should forget about small efficiencies, say about 97% of the time:
premature optimization is the root of all evil. Yet we should not pass
up our opportunities in that critical 3%

{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 1, 'CommentCount': 0, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2018:00:01/30/18', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<python><mysql><django><oop><entity-relationship>', 'Title': 'What is the most efficient way to count votes on an object?', 'ViewCount': 61, 'id': 48531942, 'user_AboutMe': '', 'user_AccountId': 31010.0, 'user_DisplayName': 'Atma', 'user_Reputation': 28003.0, 'user_Views': 1882.0, 'user_id': 84885.0}}