简体   繁体   English

如何在 DRF 中使用 ModelChoiceField?

[英]How to use ModelChoiceField in DRF?

I am trying to convert my form that was written earlier to django rest serializer but it does't work.我正在尝试将我之前编写的表单转换为 django rest 序列化程序,但它不起作用。 Could you help me to solve this problem please?你能帮我解决这个问题吗?

this is my form:这是我的表格:

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")
    )

How to built proper serializer?如何构建正确的序列化程序?

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')

Assuming you have model Country假设你有模型国家

class Country(models.Model):
    name = models.CharField(max_length=60, blank=True, default='')

You could write a serializers based on that您可以基于此编写序列化程序

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()

Now you should be able to use your desired serialized to render choices from model either as html form for instance or whatever logic fits you better现在您应该能够使用您想要的序列化来呈现模型中的选择,例如作为 html 表单或任何更适合您的逻辑

if you want it as form如果你想要它作为形式

#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>

Now if you'll create instance of Country with some name it will be shown in select dropdown, display_value function can be used to customize the option output.现在,如果您使用某个名称创建 Country 实例,它将显示在选择下拉列表中, display_value函数可用于自定义选项输出。

Hope that helps希望有帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM