这类问题一般通过ForeignKey引用解决。
# class name should begin with a capital letter and should be singular for a model
class Participant(models.Model):
username = models.CharField(max_length =50)
class Vote(models.Model)
vote_to = models.ForeignKey(Participant, on_delete=models.CASCADE, related_name='vote_to')
voted_by = models.ForeignKey(Participant, on_delete=models.CASCADE, related_name='voted_by')
date_time = models.DateTimeField(auto_now=True)
参与者的每个投票将是Votes表中的一行或Vote类型的对象。
类似的,
vote = Vote(vote_to=some_participant_object,
voted_by=someother_participant_object)
vote.save()
auto_now=True 表示该值将在创建对象时添加,因此您不必在投票时处理。
然后您可以使用 ORM 查询特定参与者的投票数。
一个基本的过滤查询就足够了。获得特定参与者的所有选票。
类似的,
# just as an idea here, the next lines might not be perfect
votes = Vote.objects.filter(voted_by__id=some_participant_id)
# or
votes = Vote.objects.filter(voted_by=some_participant_object)
# check the timestamp of the last vote and build logic accordingly
这样,编写 ORM 查询来计算特定参与者的投票数或特定参与者的投票数会更容易。