使用ListViewSet时如何在序列化器MethodField上对序列化器数据进行排序?

时间:2019-04-23 16:23:22

标签: python django django-rest-framework

我有一个说GetStudentDetails的类,我正在使用一个具有序列化器MethodField的序列化器,说postal_address,我希望基于该字段对我的结果进行排序

我尝试添加ordering =('postal_address',),由于它不是模型字段,因此遇到错误。

class GetStudentDetails(viewsets.GenericViewSet, mixins.ListModelMixin):
    model = Student
    queryset = Student.objects.all()
    serializer_class = StudentCreateSerializer
    filter_backends = 
    (filters.OrderingFilter,filters.DjangoFilterBackend,)

class StudentCreateSerializer(serializers.ModelSerializer):
    postal_address = serializers.SerializerMethodField()

    def get_postal_address(self, obj):
        return Address.objects.get(name=obj.name).address

    class Meta:
        model = Vehicle
        fields = ('name','city','state',postal_address')

class Address(models.Model):
    name=models.ForeignKey(Student, on_delete=models.CASCADE)
    address=models.CharField(max_length=60)

class Student(models.Model):
    name=models.CharField(max_length=45)
    city=models.CharField(max_length=10)
    state=models.CharField(max_length=10)

    def __str__(self):
        return name

实际结果:

[{"name":test",
"city":"abc",
"state":"def",
"postal_address":"abcdef"
},
{
"name":"test2",
"city":"aa",
"state":"bb",
"postal_address":"aabb"
}]

预期结果:

[{
"name":"test2",
"city":"aa",
"state":"bb",
"postal_address":"aabb"
},
{"name":test",
"city":"abc",
"state":"def",
"postal_address":"abcdef"
}]

1 个答案:

答案 0 :(得分:0)

我会尝试按您要合并的2个字段进行排序:

ordering = ('city', 'state')

更新:

根据您更改的条件,尝试:

ordering = ('address_set__address', )

尽管根据this post,此方法存在一些问题,即应答者通过将顺序硬编码到相关模型中来解决。因此,在您的情况下:

class Address(models.Model):
    ...
    class Meta:
        ordering = ('address',)

然后在另一个模型/序列化器中

ordering = ('address_set', )