0

I have a class say GetStudentDetails and I am using a serializer having serializer MethodField say postal_address and I want my result to be sorted on based of this field

I have tried adding ordering = ('postal_address',) and since it is not a model field, I encounter error.

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

actual result:

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

expected result:

[{
"name":"test2",
"city":"aa",
"state":"bb",
"postal_address":"aabb"
},
{"name":test",
"city":"abc",
"state":"def",
"postal_address":"abcdef"
}]
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

1 Answers1

0

I would try ordering by the 2 fields you are combining:

ordering = ('city', 'state')

UPDATE:

according to your changed criteria, try:

ordering = ('address_set__address', )

although according to this post there are issues with this method that the answerer addressed by hardcoding the ordering into the related model. So in your case:

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

then in your other model/serializer:

ordering = ('address_set', )
Verbal_Kint
  • 1,366
  • 3
  • 19
  • 35
  • Thanks for your answer and it may work in this case but say if my method field is from other model, than how would I sort now (question updated) – Aayush Bhatnagar Apr 23 '19 at 16:50
  • It didn't work for me. I had to implement list method in view and there I sorted using itemgetter from operator package. But I am looking for a solution without going in this way. – Aayush Bhatnagar Apr 25 '19 at 07:09