Django rest framework serializing many to many field

前端 未结 7 1490
旧时难觅i
旧时难觅i 2020-11-28 03:46

How do I serialize a many-to-many field into list of something, and return them through rest framework? In my example below, I try to return the post together with a list of

7条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-28 04:17

    In the serializer on init method you can pass the queryset to the field and rest_framework valide the ids on that queryset

    1) first extend your serializer from serializers.ModelSerializer

    class YourSerializer(serializers.ModelSerializer):
    

    2) include the field on the meta class

    class YourSerializer(serializers.ModelSerializer):
      class Meta:
            fields = (..., 'your_field',)
    

    3) in the init method:

    def __init__(self, *args, **kwargs):
        super(YourSerializer, self).__init__(*args, **kwargs)
        self.fields['your_field].queryset = 
    

    You can limit the queryset for that field under any argument using filter or exclude like normally you do. In case that you want include all just use .objects.all()

提交回复
热议问题