Home > Blockchain >  Django Rest Framework send queryset to serializer try SlugRelatedField
Django Rest Framework send queryset to serializer try SlugRelatedField

Time:04-01

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?

models.py

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

     class Meta:
         ordering = ["name"]

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

serializer.py

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

CodePudding user response:

  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.
...
@classmethod
def last_n_visited(cls, n: int):
    return cls.objects.order_by('last_visited')[:n-1]


@property
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
  • Related