django rest框架:订购不正常

时间:2017-11-22 09:11:36

标签: django-rest-framework

我有一个名为typeofingredient的ForeignField模型。

如果我尝试以下序列化程序类

class IngredientListSerializer(ModelSerializer):
    class Meta:
        model = Ingredient
        fields = '__all__'

然后我尝试http://localhost:8000/api/ingredients/?ordering=typeofingredient

结果全部按w.r.t排序为typeofingredient的id。

后来我在api中显示typeofingredient而不是id的名称字段。所以我将序列化程序类改为以下:

class IngredientListSerializer(ModelSerializer):
    typeofingredient = ReadOnlyField(source='typeofingredient.name')
    class Meta:
        model = Ingredient
        fields = '__all__'

然后我尝试http://localhost:8000/api/ingredients/?ordering=typeofingredient,它根本没有对结果进行排序。

如何解决这个问题

1 个答案:

答案 0 :(得分:0)

我找到了答案

https://github.com/encode/django-rest-framework/issues/1005https://github.com/encode/django-rest-framework/pull/5533

所以我更新了我的djangrestframework:

$ pip install djangorestframework -U
Collecting djangorestframework
  Downloading djangorestframework-3.7.3-py2.py3-none-any.whl (1.5MB)
    100% |████████████████████████████████| 1.5MB 447kB/s 
Installing collected packages: djangorestframework
  Found existing installation: djangorestframework 3.3.3
    Uninstalling djangorestframework-3.3.3:
      Successfully uninstalled djangorestframework-3.3.3
Successfully installed djangorestframework-3.7.3

然后一切都运作良好

class IngredientListSerializer(ModelSerializer):
    typeofingredient = ReadOnlyField(source='typeofingredient.name',default=None)
    class Meta:
        model = Ingredient
        fields = '__all__

http://localhost:8000/api/ingredients/?ordering=-typeofingredienthttp://localhost:8000/api/ingredients/?ordering=typeofingredient

运作良好 “