Home > front end >  Need help in asinging values for Choices in Choice Field in Django
Need help in asinging values for Choices in Choice Field in Django

Time:06-21

models.py

class Survey_Answer(models.Model):
    
    CHOICES = [('Disagree Strongly', 'Disagree Strongly'),
            ('Disagree', 'Disagree'),
            ('Undecided', 'Undecided'),
            ('Agree', 'Agree'),
            ('Agree Strongly', 'Agree Strongly')]
    
    question = models.ForeignKey(Survey_Question, on_delete=models.CASCADE)
    answer_text = models.CharField(max_length=20, choices=CHOICES, default='Undecided')
    date_published = models.DateTimeField('date published', auto_now_add=True)
    created_at = models.DateTimeField('created at', auto_now_add=True)

    
    def __str__(self):
        return self.answer_text   ' -  '   self.question.question_text

This is my models.py. I need help in assigning value for a particular option in CHOICES( Eg: 5 points for Agree Strongly option). If a user selects an option from choices, he should be getting points based on the option he selected

CodePudding user response:

If you want to use choices, you can use them as tuples.

CHOICES = (('Disagree Strongly', 'Disagree Strongly'),
        ('Disagree', 'Disagree'),
        ('Undecided', 'Undecided'),
        ('Agree', 'Agree'),
        ('Agree Strongly', 'Agree Strongly'))

Insted of [] use ().

CodePudding user response:

you can override the save method of the model.

class Survey_Answer(models.Model):

 def save(self,*args, **kwargs):
 **Do Stuff whatever you want** //Give points to users
 super(Survey_Answer, self).save(*args, **kwargs)
  • Related