首页 > 解决方案 > 如何在投票系统的 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()

标签: djangodjango-models

解决方案


您没有保存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')

推荐阅读