我正在尝试将之前编写的表单转换为django rest序列化器,但无法正常工作。您能帮我解决这个问题吗?
这是我的表格:
class TripSearchForm(forms.Form):
departure = ModelChoiceField(
queryset=Place.objects.places_for_segment(), widget=autocomplete.ModelSelect2(url="autocomplete")
)
destination = ModelChoiceField(
queryset=Place.objects.places_for_segment(), widget=autocomplete.ModelSelect2(url="autocomplete")
)
如何构建适当的序列化器?
class SearchSerializer(serializers.Serializer):
departure = serializers.RelatedField(queryset=places_models.Place.objects.all(),
label='departure')
destination = serializers.RelatedField(queryset=places_models.Place.objects.all(),
label='destination')
答案 0 :(得分:0)
假设您有国家(地区)模型
class Country(models.Model):
name = models.CharField(max_length=60, blank=True, default='')
您可以基于此写一个序列化器
class CountryField(serializers.PrimaryKeyRelatedField):
def display_value(self, instance):
return instance.name
class CountrySerializer(serializers.ModelSerializer):
country = CountryField(queryset=Country.objects.all())
class Meta:
model = Country
fields = ('name', )
class DesiredSerializer(serializers.Serializer):
country = ColorSerializer()
现在,您应该能够使用所需的序列化来呈现模型中的选择,例如以html形式或更适合您的逻辑
如果您希望将其作为表格
#views.py
def get(self, request):
serializer = DesiredSerializer()
return Response({ 'serializer': serializer }, template_name='my_model_choices_form.html')
<!-- my_model_choices_form.html -->
{% load rest_framework %}
<form action="..." method="POST">
{% csrf_token %}
{% render_form serializer %}
</form>
现在,如果您要创建具有某些名称的Country实例,它将显示在选择下拉列表中,则display_value
函数可用于自定义选项输出。
希望有帮助