1

I think I am just putting this code in the wrong place but was wondering if someone could help out here. I wanted to get an item from the db for the last business day. This works fine, but it seems the below gets compiled when i start the app with gunicorn. So now the current_b_day is evaluated as 11/13 (today = 11/16). But this never changes. So my viewset will always return the same dataset even though i am adding new data to the db via an alternate process. If i bring the server down and back up, it will recompile and get a new value for current_b_day. Any help is much appreciated!

views.py

from pandas.tseries.offsets import BDay, BMonthEnd, BYearEnd
from datetime import date, datetime

    class YieldCurveViewSet(viewsets.ModelViewSet):
        current = date.today()
        current_b_day = current - BDay(1)  #This never changes and is compiled in!
    
        queryset = YieldCurve.objects.filter(create_date=current_b_day)
        serializer_class = YieldCurveSerializer
bmccormick
  • 75
  • 1
  • 8

1 Answers1

1

According to the Django Rest Framework documentation the queryset you're using is evaluated only once.
To force re-evaluation for each request you should implement the get_queryset method in the ViewSet.

For a simple filter where your model has a Foreign Key User:

def get_queryset(self):
    return YieldCurve.objects.filter(user = self.request.user)

Or in your case:

def get_queryset(self):
    current = date.today()
    current_b_day = current - BDay(1)    
    return YieldCurve.objects.filter(create_date=current_b_day)

Hope this works!

Edit: if it doesn't work, copy the function from the linked page and add your functionality. I provided code that works in our codebase, so I left the extra functions out.

  • 1
    Thanks! I knew the answer was in the documentation I just couldn't think of what to search for. I am running it through debug and can see it is being evaluated everytime I hit the URL. Thanks again! – bmccormick Nov 17 '20 at 18:59