Follow up onto:
AutoField should be present but it's not (django)?
related to:
"Cannot update a query once a slice has been taken". Best practices?
I don't need to filter objects, only order by date and select the most recent one:
def get_latest_currency(self):
"""
Return most up to date value
"""
up_to_date_currency = Currency.objects.order_by('-currency_value_in_dollars_date')[:1]
if not up_to_date_currency.exists():
# No objects yet; fetch currencies
update_coins_table()
return Currency.objects.order_by('-currency_value_in_dollars_date')[:1]
up_to_date_currency is initialized correctly; the last line gives:
assert not self.query.is_sliced, \
AssertionError: Cannot filter a query once a slice has been taken.
This code represents a view (I want to return a plain JSON object (this is a REST endpoint)). Why is django complaining about a filter when only a slice was used?
get_latest_currency is the name of the endpoint:
import sys
from django.urls import path
from . import views
app_name = 'manage_crypto_currency'
urlpatterns = [
path('get_currency/', views.get_latest_currency, name='index'),
]
Stacktrace:
Internal Server Error: /get_currency/
Traceback (most recent call last):
File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\utils\deprecation.py", line 116, in __call__
response = self.process_response(request, response)
File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\middleware\clickjacking.py", line 26, in process_response
if response.get('X-Frame-Options') is not None:
File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\db\models\query.py", line 418, in get
clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs)
File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\db\models\query.py", line 942, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\db\models\query.py", line 954, in _filter_or_exclude
assert not self.query.is_sliced, \
AssertionError: Cannot filter a query once a slice has been taken.
Tried wrapping the objects around HttpReponse():
return HttpResponse(Currency.objects.order_by('-currency_value_in_dollars_date')[:1], content_type='application' '/json')
This works but only the name is, for some reason, returned.