我在这里显示了一个多选择字段:
ratesheets = serializers.MultipleChoiceField(choices=RATESHEET_CHOICES, allow_blank=False)
此处填充了和RATESHEET_CHOICES(也在上下文中显示了上述内容):
class RatesheetsComparisonSerializer(serializers.HyperlinkedModelSerializer):
RATESHEET_CHOICES = []
def __init__(self, *args, **kwargs):
for 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)
我遇到的唯一问题是MultipleChoiceField保持不变,直到我重新启动服务器。每次加载页面时如何更新选项。我是否需要在其他地方放置相同的代码?我花了很长时间才到达这里,我找不到任何有助于我的东西。谢谢!
答案 0 :(得分:2)
将ratesheets
字段添加为类变量(它们是静态的!),但是在__init__
方法中:
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)
(我假设这些序列化程序的工作方式类似于Django表单,self.fields
是猜测,并且该字典的名称可能不同)
编辑:还需要一件事
从以下位置更改Meta类:
class Meta:
model = RatesheetsComparison
fields = ('created', 'ratesheets',)
read_only_fields = ('created',)
为:
class Meta:
model = RatesheetsComparison
fields = ('created',)
read_only_fields = ('created',)
或者你会得到一个ImportError,因为它认为费率表存在但无法找到它。