【发布时间】:2014-05-18 07:41:09
【问题描述】:
我正在写一份选举申请。在这个过程中,我定义了一个 Election 模型和一个 Candidate 模型。
注意:我使用的是 Django 版本 1.3.7,Python 2.7.1。
选举方法之一,
Election.count_first_place(self)
旨在计算每个候选人获得的第一名选票数量并更新候选人的 numVotes 属性。但由于某种原因,无论选票如何,它们都保持为零。
注意:我正在实施 STV,因此每张选票都包含一个候选人数组(ballot.voteArray),按照最喜欢(位置零)到最不喜欢(位置 n)的顺序排列。我已经用 PickledObjectField 实现了这个列表(参见link)。
models.py
class Candidate(models.Model):
election = models.ForeignKey("Election")
numVotes = models.FloatField(blank=True)
class Ballot(models.Model):
election = models.ForeignKey("Election", related_name = "ballot_set")
voteArray = PickledObjectField(null=True,blank=True)
class Election(models.Model):
position = models.CharField(max_length = 50)
candidates = models.ManyToManyField(Candidate,related_name="elections_in",null=True,blank=True)
def count_first_place(self):
#retrieve all of the ballots cast in this election
ballots = Ballot.objects.filter(election = self)
for ballot in ballots.all():
# the first element of a ballot's voteArray is a Candidate object
first_place_choice = ballot.voteArray[0]
first_place_choice.numVotes += 1
first_place_choice.save()
ballot.save()
self.save()
这是我运行测试时发生的情况:
注意:我意识到我节省的频率超出了必要的程度。只是在我测试这个东西时绝对确定它会在需要时保存。
elec = Election(position="Student Body President")
elec.save()
j = Candidate(election=elec,numVotes=0)
j.save()
e = Candidate(election=elec,numVotes=0)
e.save()
b = Candidate(election=elec,numVotes=0)
b.save()
elec.candidates.add(j,e,b)
elec.save()
ballot1 = Ballot(election=elec,voteArray=[j,e,b])
ballot1.save()
ballot2 = Ballot(election=elec,voteArray=[j,b,e])
ballot2.save()
ballot3 = Ballot(election=elec,voteArray[e,b,j])
ballot3.save()
所以在这个位之后,j 有两个 2 位投票,e 有 1。但是当我运行时
elec.count_first_place()
j 仍然有零票,e 和 b 也是如此。
这是怎么回事???
【问题讨论】:
标签: mysql database django model