There are two way to achieve this. Either use choices tuple with your desired value or override save method of the model.
1ST OPTION:
class Survey_Answer(models.Model):
CHOICES = (('Disagree Strongly', '1'),
('Disagree', '2'),
('Undecided', '3'),
('Agree', '4'),
('Agree Strongly', '5'))
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
It simply means user will select the left option(1st element of the tuple) and you can use the right option(2nd element of the tuple) for your processing. So if user selects 'Agree Strongly' you will have '5' value as well. You can then use serializers to show that value. The syntax for using this will be get_your_field_display.
serializers.py file
from rest_framework import serializers
class SurveySerializer(serializers.ModelSerializer):
value = serializers.Charfield(source = 'get_answer_text_display', read_only = True)
class Meta:
model = Survey_Answer
fields = ('question', 'answer_text', 'date_published', 'value') # assuming that you don't want users to see created at field
please note that value is a custom field in the serializer.
2ND OPTION:
2nd and preferred option would be to add another field in your model and override save method to add this value
models.py
class Survey_Answer(models.Model):
CHOICES = (('Disagree Strongly', '1'),
('Disagree', '2'),
('Undecided', '3'),
('Agree', '4'),
('Agree Strongly', '5'))
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)
value = models.IntegerField()
def save(self,*args, **kwargs):
self.value = # add your value based based on if else or above trick used in serializers
super(Survey_Answer, self).save(*args, **kwargs)
def __str__(self):
return self.answer_text + ' - ' + self.question.question_text