我正在构建一个有问题的简单应用程序。每个问题都会有一个二元投票(是/否)。我想记录每个用户的投票,所以每个用户每个问题只能得到一个投票(类似于堆栈溢出或reddit)。从模型保存方法操作另一个模型的数据
我在这个问题上有一个vote_no和votes_yes int字段。每次添加投票时,这些都需要在交易中更新。我可以从Vote模型的保存方法中做到这一点吗?
class Question(models.Model):
part_isit = models.CharField(max_length=45)
part_if = models.CharField(max_length=90)
votes_no = models.IntegerField()
votes_yes = models.IntegerField()
author = models.ForeignKey(User)
create_date = models.DateField(auto_now_add=True)
VOTE_CHOICES = (
('Y', 'Yes'),
('N', 'No'),
)
class Vote(models.Model):
choice = models.CharField(max_length=1, choices=VOTE_CHOICES)
question = models.ForeignKey(Question)
author = models.ForeignKey(User)
create_date = models.DateField(auto_now_add=True)
def save(self):
# increment the questions vote totals
#save the vote
super(Vote, self).save();
它的工作原理,谢谢。我唯一不喜欢的是可扩展性。它将检索所有投票对象作为列表。我宁愿让ORM做聚合查询。 BTW有一个错字(选择应该是选择)。 – Keyo 2010-12-18 07:53:27
我的错误,就是如何在ORM中完成计数查询。 – Keyo 2010-12-18 08:10:04