[Answered ]-Multiplechoicefield – how to update the list of choices on each page load

2👍

add the ratesheets field not as a class variable (which are static!) but in the __init__ method:

class RatesheetsComparisonSerializer(serializers.HyperlinkedModelSerializer):

    def __init__(self, *args, **kwargs):
        super(RatesheetsComparisonSerializer, self).__init__(*args, **kwargs)
        RATESHIELD_CHOICES = []
        for rs in RateSheet.objects.all():
            RATESHEET_CHOICES.append((rs.pk, rs.title))
        self.fields['ratesheets'] = serializers.MultipleChoiceField(choices=RATESHEET_CHOICES, allow_blank=False)

(I’m assuming these serializers work similar to Django forms, self.fields is a guess and that dictionary might be named differently)

Edit: one more thing needed

Change the Meta class from:

class Meta:
    model = RatesheetsComparison
    fields = ('created', 'ratesheets',)
    read_only_fields = ('created',)

to:

class Meta:
    model = RatesheetsComparison
    fields = ('created',)
    read_only_fields = ('created',)

or else you’ll get an ImportError because it thought ratesheets existed but couldn’t find it.

Leave a comment