[Answered ]-DjangoREST – How can I make my view/serializer more efficient on the server?

1👍

You could make them properties on the model.

class Bucket(models.Model):
    ...

    @cached_property
    def symbols_unicode(self):
        if not self.stock_list:
            return None
        return (','.join(map(str, self.stock_list)))

    @cached_property
    def bucket_return(self):
        if not self.symbols_unicode:
            return None

        postgrest_urls = f"http://localhost:3000/rpc/bucketreturn?p_stocks=%7B{self.symbols_unicode}%7D"
        bucket_return = requests.get(postgrest_urls, headers={'Content-Type': 'application/json'}).json()
        return bucket_return


    @cached_property
    def bucket_sectors(self):
        if not self.symbols_unicode:
            return None

        postgrest_urls = f"http://localhost:3000/rpc/bucketsectors?p_stocks=%7B{self.symbols_unicode}%7D"
        bucket_sectors = requests.get(postgrest_urls, headers={'Content-Type': 'application/json'}).json()
        return bucket_sectors

Then your serializer can be something like this:

class BucketListExtraDataSerializer(serializers.ModelSerializer):
    
    class Meta:
        model = Bucket
        fields = ('id', 'stock_list', 'bucket_return', 'bucket_sectors')

Generally, I don’t like to do much actual work in a SerializerMethodField, especially if that same logic will be used elsewhere.

This just shows how you can use attributes in serializers. It does not attempt to address the fact that you’re making two external requests during serialization of a single object, but I don’t think that’s what you meant by optimizing in your question.

👤synic

Leave a comment