I am trying to return a value
from get_queryset
.
def get_queryset(self):
if self.request.user.is_superuser:
return StockPriceModel.objects.order_by('ticker').distinct()
elif not self.request.user.is_authenticated:
print('in')
print(self.request.data)
last_price = StockPriceModel.objects.all().filter(
ticker=self.request.data['ticker']).order_by('-last_date_time')[0].last_price
print(last_price)
return last_price
last price gets printed without an issue.
In return
I get various errors:
TypeError at /api/stock-prices-upload/ 'float' object is not iterable
If I try to return
till:
StockPriceModel.objects.all().filter(
ticker=self.request.data['ticker']).order_by('-last_date_time')
It works.
As soon as I try to return just the 0
position queryset I get errors.
I assume this is because get_queryset
is supposed to return a queryset
. Not sure how to return just the value.
Edit:
I am now trying to get only the latest row ie [0]
form the data but still getting the same errors ie
StockPriceModel object is not iterable
# The current output if I don't add the [0] i.e. try to get the last row of data
[{"id":23,"last_price":"395.2","name":null,"country":null,"sector":null,"industry":null,"ticker":"HINDALCO","high_price":null,"last_date_time":"2022-10-20T15:58:26+04:00","created_at":"2022-10-20T23:20:37.499166+04:00"},{"id":1717,"last_price":"437.5","name":null,"country":null,"sector":null,"industry":null,"ticker":"HINDALCO","high_price":438.9,"last_date_time":"2022-11-07T15:53:41+04:00","created_at":"2022-11-07T14:26:40.763060+04:00"}]
Expected response:
[{"id":1717,"last_price":"437.5","name":null,"country":null,"sector":null,"industry":null,"ticker":"HINDALCO","high_price":438.9,"last_date_time":"2022-11-07T15:53:41+04:00","created_at":"2022-11-07T14:26:40.763060+04:00"}]
I have tried using last
, get
etc. Just won't work.
Because, get_queryset()
always return a queryset of objects or a list of objects.
You cannot return an object or a field from the get_queryset
method.
the last_price
value will be printed, but it is a field value and therefore the get_queryset
method will not return it.
When you add [0]
, it takes the first object from the filtered queryset. Till that point, it is a queryset of objects.
This is a bit hacky, and I am sure there must be a better way to do this.
I wanted to get return
of either a single row (last_date_time) based or the last_price
value.
I wrapped the query:
# removed the .last_price
last_price = StockPriceModel.objects.all().filter(
ticker=self.request.data['ticker']).order_by('-last_date_time')[0]
last_price = [last_price] # made it into a list, i.e. iterable
return last_price
And now I can get the last row.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.