Django Rest Framework send queryset to serializer try SlugRelatedField


Hi i am trying to send ordered query to my parent serializer try slug related field but i am getting "Object of type Supplier is not JSON serializable". i have also tried to make a "serializers.SerializerMethodField()" but i am getting the same error. is there a way to do something similar? in my model i am ordering it by name so i need to do another query so that i can order it by last visited. Should i make new model serialzier and make query there and pass it to parent serializer?

     last_visited = models.DateTimeField(auto_now_add=True, null=True)

     class Meta:
         ordering = ["name"]

     def last_4_visited(self):
        return Supplier.objects.order_by('last_visited')[3]

 suppliers = serializers.SlugRelatedField(slug_field='last_4_visited', many=True, read_only=True)


  1. It’s not really a good way to hardcode number of visited in your property, i.e. make method for abstract n and then use in your property.
def last_n_visited(cls, n: int):
    return cls.objects.order_by('last_visited')[:n-1]

def last_4_visited(self):
    return type(self).last_n_visited(4)

  1. To answer your question.
class SupplierSerializer(serializers.ModelSerializer):
    class Meta:
        model = Supplier
        fields = "__all__"

# and then in your other serializer or even in this one:
class SomeSerilializer(...):
    last_4_visited = serializers.SerializerMethodField(method_name="get_last_4_visited")

    def get_last_4_visited(self, obj):
        suppliers = Supplier.last_n_visited(4)
        return SupplierSerializer(suppliers, many=True).data

Answered By – Nikita

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published