django - 如何在投票系统的 Django 数据库中增加投票字段
问题描述
我正在尝试建立一个系统,在该系统中,一个人(选民)将针对候选人的“候选人 ID”投票给候选人,因此该选民必须输入“酋长国 ID”(这是选民的主键)和“选举” Id' - 这是投票站的主键 - 这两个 ID 都将被验证以检查是否已投票,但问题确实在我的逻辑之内。这是我的 Views.py:
def vote(request):
can_id_obj = Candidate_Form.objects.get(pk=request.POST['Can_ID'])
voterrecord = Election_Day( #through this we will create an object of the class or our model
Can = can_id_obj, #these are the fields in my 'Election Day' model
emirates_id = Emirates_ID,
election_id = Election_ID
)
voterrecord.Vote += 1 #we will call a field to manipulate it
voterrecord.save() #finally we can call save method on the object
return render(request, 'Election_Day.html')
每次投票时,它不会增加先前投票的相同记录,而是会创建一个新记录,然后将投票保存为 1,所以基本上我希望它增加相同的记录,如果投票已经为同一个候选人投票。我希望你能理解解释..
Models.py供参考
class Election_Day(models.Model):
Can = models.ForeignKey('Candidate_Form', on_delete=models.CASCADE) #you refer the primary key to the whole class and it will automatically pick the id (primary key) of that class and make it a foreign key #with that you can also access all the data stored in that table
Elec = models.ForeignKey('Election_Info', on_delete=models.CASCADE, null =
True) #you can make a foreign key null
Vote = models.IntegerField(default=0)
emirates_id = models.IntegerField()
election_id = models.IntegerField()
解决方案
您没有保存Candidate_Form
对象。最后像这样添加can_id_obj.save()
。
def vote(request):
can_id_obj = Candidate_Form.objects.get(pk=request.POST['Can_ID'])
voterrecord = Election_Day( #through this we will create an object of the class or our model
Can = can_id_obj, #these are the fields in my 'Election Day' model
emirates_id = Emirates_ID,
election_id = Election_ID
)
can_id_obj.Vote += 1 #we will call a field to manipulate it
can_id_obj.save()
voterrecord.save() #finally we can call save method on the object
return render(request, 'Election_Day.html')
推荐阅读
- android - 使用 Intent 创建笔记时 Evernote 崩溃
- sockets - 有没有一种方法可以在不使用多播的情况下将一个数据包发送给 UDP 中的多个收件人?
- wordpress - Wordpress 中的插件管理页面
- angular - 如何仅将一个值从一个组件传递给Angular 6中的另一个组件?
- c# - 如何使用 Unity 初始化 Firebase 实时数据库?
- javascript - onselectionchange 更新时变量不更新
- python - Boto3 Python 只获取某些文件类型?
- c# - Visual Studio 2017 想要引用已使用不同程序集引用的内容
- javascript - Angular5 - 从类中新创建的对象返回未定义
- c# - Webrtc Capture Desktop Audio without using vb-audio cable driver for Native Windows