Alejandro Veintimilla
Alejandro Veintimilla

Reputation: 11523

Django Class Based View acces a variable set in get_context in the get_queryset method

If I have a variable I set in the get_context_data function, is there a way to access that variable in the get_queryset function?

def get_context_data(self, **kwargs):
    coindex_btc_price = requests.get("http://api.coindesk.com/v1/bpi/currentprice.json")

def get_queryset(self, **kwargs):
    coindex_btc_price = requests.get("http://api.coindesk.com/v1/bpi/currentprice.json")

I don't want to set it two times like that.

Upvotes: 0

Views: 61

Answers (1)

2ps
2ps

Reputation: 15926

I would refactor and create an instance variable that holds the value for you:

def __init__(self):
    super(ClassName, self).__init__()
    self.coindex_btc_price = None

def get_coindex_price(self):
    if self.coindex_btc_price is None:
        self.coindex_btc_price = coindex_btc_price = requests.get("http://api.coindesk.com/v1/bpi/currentprice.json")
    return self.coindex_btc_price

def get_context_data(self, **kwargs):
    coindex_btc_price = self.get_coindex_price()

def get_queryset(self, **kwargs):
    coindex_btc_price = self.get_coindex_price()

Upvotes: 3

Related Questions