python - multiplechoicefield - how to update the list of choices on each page load -
i have multiplechoicefield shown here:
ratesheets = serializers.multiplechoicefield(choices=ratesheet_choices, allow_blank=false) and ratesheet_choices populated here (also showing above in context):
class ratesheetscomparisonserializer(serializers.hyperlinkedmodelserializer): ratesheet_choices = [] def __init__(self, *args, **kwargs): rs in ratesheet.objects.all(): self.ratesheet_choices.append((rs.pk, rs.title)) super(ratesheetscomparisonserializer, self).__init__(*args, **kwargs) ... ratesheets = serializers.multiplechoicefield(choices=ratesheet_choices, allow_blank=false) the problem i'm having multiplechoicefield stays same until restart server. how update choices each time load page. need put same code somewhere else? it's taken me long time here , can't find kind of stuff seem me. thanks!
add ratesheets field not class variable (which static!) in __init__ method:
class ratesheetscomparisonserializer(serializers.hyperlinkedmodelserializer): def __init__(self, *args, **kwargs): super(ratesheetscomparisonserializer, self).__init__(*args, **kwargs) rateshield_choices = [] 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 django forms, self.fields guess , dictionary might named differently)
edit: 1 more thing needed
change 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 importerror because thought ratesheets existed couldn't find it.
Comments
Post a Comment