0

I have been trying to use get_name_display() in my API View but it does not display the text, just number. I have checked the documentation but it does not mention anything about it - it should be working. May it have something to do with perform_update() method? For instance, the folowing code prints 3 instead of 'GaussianNB'.

Model

class Algorithm(models.Model):
    ALGORITHM_NAME = (
        (0, 'KNeighborsClassifier'),
        (1, 'LogisticRegression'),
        (2, 'LinearSVC'),
        (3, 'GaussianNB'),
        (4, 'DecisionTreeClassifier'),
        (5, 'RandomForestClassifier'),
        (6, 'GradientBoostingClassifier'),
        (7, 'MLPClassifier'),
    )

    name = models.CharField(max_length=64, choices=ALGORITHM_NAME)
    parameters = JSONField()

View

class CalcUpdateView(UpdateAPIView):
    queryset = Calc.objects.all()
    serializer_class = CalcSerializer

    def perform_update(self, serializer):
        instance = serializer.save()
        algorithm = Algorithm.objects.get(pk=self.request.data['algorithm'])
        print(algorithm.get_name_display())

Thanks in advance for help!

maslak
  • 1,115
  • 3
  • 8
  • 22
  • [This](https://stackoverflow.com/questions/28945327/django-rest-framework-with-choicefield) might be help you. – uedemir Jan 24 '19 at 13:38
  • 1
    Probably the fact that `name` is a `CharField` but the first element of each tuple in `ALGORITHM_NAME` is an integer is bothering Django in some way? Try either changing the first element of each tuple to a string or changing the `name` field to an `IntegerField` – ivissani Jan 24 '19 at 13:48
  • ivissani, do not know why, but changing numbers to strings has helped! – maslak Jan 24 '19 at 13:53
  • 1
    I will transform the comment into an answer then – ivissani Jan 24 '19 at 15:12

1 Answers1

2

Probably the fact that name is a CharField but the first element of each tuple in ALGORITHM_NAME is an integer is bothering Django in some way. Try either changing the first element of each tuple to a string:

ALGORITHM_NAME = (
    ('0', 'KNeighborsClassifier'),
    ('1', 'LogisticRegression'),
    ('2', 'LinearSVC'),
    ('3', 'GaussianNB'),
    ('4', 'DecisionTreeClassifier'),
    ('5', 'RandomForestClassifier'),
    ('6', 'GradientBoostingClassifier'),
    ('7', 'MLPClassifier'),
)

or changing the name field to an IntegerField:

name = models.IntegerField(choices=ALGORITHM_NAME)
ivissani
  • 2,614
  • 1
  • 18
  • 12