我想了解在什么级别编写代码来控制django序列化程序返回的顺序。必须在模板级别,模型级别或序列化程序级别完成。是什么决定了任何序列化程序返回的JSON中的字段顺序?在我的示例中,考虑这些序列化程序类:
class FilterURLSerializer(serializers.Serializer):
active = serializers.CharField(read_only=True)
inactive = serializers.CharField(read_only=True)
class FacetedFilterOptionsSerializer(serializers.Serializer):
name = serializers.CharField(read_only=True)
slug = serializers.CharField(read_only=True)
count = serializers.IntegerField(read_only=True)
active = serializers.BooleanField(read_only=True)
urls = FilterURLSerializer(read_only=True)
class FacetedFilterSerializer(serializers.Serializer):
name = serializers.CharField(read_only=True)
slug = serializers.CharField(read_only=True)
options = FacetedFilterOptionsSerializer(source='options')
并返回此JSON数据:
{'name': u'Skill level', 'slug': u'skill', 'options': [{'name': u"I'm Learning", 'slug': u'beginner', 'count': 0, 'active': False, 'urls': {'active': u'/en-US/search?skill=beginner', 'inactive': u'/en-US/search'}}, {'name': u"I'm an Expert", 'slug': u'advanced', 'count': 0, 'active': False, 'urls': {'active': u'/en-US/search?skill=advanced', 'inactive': u'/en-US/search'}}, {'name': u'Intermediate', 'slug': u'intermediate', 'count': 0, 'active': False, 'urls': {'active': u'/en-US/search?skill=intermediate', 'inactive': u'/en-US/search'}}]}
我想知道是什么决定了JSON中这些字段的顺序,我该如何以我想要的方式更改它?
答案 0 :(得分:0)
如果您想要订购字段名称,可以尝试以下方法:
myList = list(yourmodel.objects.values('filed1','field2').filter(someid=i).orderby('column'))