在 django-rest 管理视图中排序相关模型值

Ordering related model values in django-rest admin view

我想查看此视图​​,其中功能列表 按字母顺序排序。

上图的模型来自AircraftModel.

models.py:

class AircraftModelFeature(models.Model):
    name = models.CharField(max_length=60)

    def __str__(self):
        return self.name

class AircraftModel(models.Model):
    features_list = models.ManyToManyField(AircraftModelFeature)
    # ... other stuff ...

    def __str__(self):
        return self.name

serializers.py

class AircraftModelFeatureSerializer(serializers.ModelSerializer):
    class Meta:
        model = AircraftModelFeature
        fields = "__all__"

class AircraftModelSerializer(serializers.ModelSerializer):
    features_list = AircraftModelFeatureSerializer(many=True, read_only=True)
    # ...other stuff...

    class Meta:
        model = AircraftModel
        fields = ['id', 'features_list',] # there are more fields, omitted

views.py

class AircraftModelFeatureViewSet(viewsets.ReadOnlyModelViewSet):
    permission_classes = [IsAdminOrReadOnly]
    queryset = AircraftModelFeature.objects.all().order_by('name')
    serializer_class = AircraftModelFeatureSerializer
    
class AircraftModelViewSet(viewsets.ReadOnlyModelViewSet):
    permission_classes = [IsAdminOrReadOnly]
    queryset = AircraftModel.objects.all().order_by('name')
    serializer_class = AircraftModelSerializer

那么,我怎样才能使该列表排序?

深入研究 Django docs,我找到了解决方案:修改 Admin Django 应用程序正在使用的模型 class。我必须编辑的文件是 admin.py.

admin.py之前:

from django.contrib import admin
from pubapi.models import AircraftModelOptional

admin.site.register(AircraftModelOptional)

admin.py 之后:

from django.contrib import admin
from pubapi.models import AircraftModelOptional

class AircraftModelOptionalAdmin(admin.ModelAdmin):
    ordering = ['name']

admin.site.register(AircraftModelOptional, AircraftModelOptionalAdmin)

我得到的:

如所写here可以编辑 Admin Django 应用程序正在使用的模型。

如所写here可以按模型字段对列表进行排序。