按子字段对嵌套序列化器字段的 DRF 序列化器输出进行排序

phy*_*ion 6 sorting django serialization django-rest-framework

我有两个序列化器,其中一个序列化器通过关系引用另一个序列化器many=True

class AttributeInParentSerializer(ModelSerializer):
    masterdata_type = CharField(max_length=256, source='masterdata_type_id')

    class Meta:
        model = Attribute
        fields = ('uuid', 'masterdata_type')

class ArticleInArticleSetSerializer(ModelSerializer):
    attributes = AttributeInParentSerializer(many=True)

    class Meta:
        model = Article
        fields = ('uuid', 'attributes')    
Run Code Online (Sandbox Code Playgroud)

Article 中属性的顺序并不总是相同,但我想以相同的顺序输出它们,因此在本例中对 field 进行排序masterdata_type。我怎样才能做到这一点?请注意,如果可能的话,我不想更改序列化器的任何客户端,当然也不想更改任何模型。

Sat*_*tan 14

旧线程,但因为它仍然出现在谷歌上,我也想分享我的答案。尝试覆盖该Serializer.to_representation方法。现在您基本上可以做任何您想做的事情,包括自定义响应的排序。在你的情况下:

class ArticleInArticleSetSerializer(ModelSerializer):
    attributes = AttributeInParentSerializer(many=True)

    class Meta:
        model = Article
        fields = ('uuid', 'attributes')

    def to_representation(self, instance):
        response = super().to_representation(instance)
        response["attributes"] = sorted(response["attributes"], key=lambda x: x["masterdata_type"])
        return response
Run Code Online (Sandbox Code Playgroud)