Django Rest Framework ManyToMany字段排序

时间:2018-09-25 23:02:00

标签: python django django-rest-framework

我有以下型号:

class BusStop(m.Model):
    street_name = m.CharField(max_length=255)

    class Meta:
        ordering = ['street_name']
    ...

class Carrier(m.Model):
    name = m.CharField(max_length=255)
    ...

class CarrierStop(m.Model):
    bus_stop = m.ManyToManyField(BusStop, related_name='carrier_stop_fk')
    carrier = m.ForeignKey(Carrier, on_delete=m.CASCADE, related_name='test_carrier_fk')

我做了序列化器:

    class CarrierStopSerializer(serializers.ModelSerializer):
        carrier = serializers.StringRelatedField()
        bus_stop = serializers.StringRelatedField(many=True)

             class Meta:
                    model = CarrierStop
                    fields = ['id', 'carrier', 'bus_stop']

我有一些BusStop模型的对象,并且序列化程序提供了这样的表示形式:

    [
        {
            "id": 1,
            "carrier": "Fremiks",
            "bus_stop": [
                    "Armii Krajowej",
                    "Kino Lot 01",
                    "Kosynierów I 02"
            ]
        }
    ]
CarrierStopSerializer中的

bus_stop字段返回按名称排序的公共汽车站。我想在Django ManyToMany字段创建的中间表carrierstop_bus_stop中按ID排序。我知道我应该使用SerializerMethod字段而不是StringRelatedField(或PrimaryKeyRelatedField,不要紧),但是我不确定如何准确地做到这一点。

1 个答案:

答案 0 :(得分:3)

使用SerializerMethodField作为

class CarrierStopSerializer(serializers.ModelSerializer):
    carrier = serializers.StringRelatedField()
    bus_stop = serializers.SerializerMethodField(read_only=True)

    def get_bus_stop(self, model):
        return [bus_stop.__str__() for bus_stop in model.bus_stop.all().order_by('id')]

    class Meta:
        model = CarrierStop
        fields = ['id', 'carrier', 'bus_stop']